1

我有产品

(index0)- 名称=计算机,ID = 1

(index1)- 名称=鼠标,ID= 2

(index2)- 名称=键盘,ID = 3

(index3)- 名称=笔记本电脑,ID = 4

例如,

var result = context.Products.where(s=>s.Id==3).firstordefault();

如何在 c# 中使用实体框架找到 Id=3 产品的索引?

4

2 回答 2

2

我不确定您要将索引用于什么,而且我认为DBSet<TEntity>.

您可以使用以下方法从Local您的属性中获取索引:DBSetFindIndex

 context.Products.Local.IndexOf(...)

但我敢肯定,无论您尝试做什么,都有更好的方法。

此外,Id如果您知道对象的 ID,则假设是对象的主键,您可能应该使用它Find来获取您的实体:

var result = context.Products.Find(Id); // Id = 3.
于 2013-08-09T19:20:13.233 回答
0

您没有提及 (index..) 项目的类型,但我们假设它是一个 int。事实上,它可以是任何类型。

您的 (index..) 项目是主键,假设它们在属性索引中:

您的产品类将是:

class Product
{
    [Key]
    public int Index {get; set;}

    public string Name {get; set;}
    public int Id {get; set;}

    // etc.
 }

你的 DbContext 会是这样的:

public class MyDbContext : DbContext
{
    public DbSet<Product> Products {get; set;}
    ...
}

获取 Id == 3 的所有产品,并获取这些产品的指数:

using (var dbContext = new MyDbContext(...))
{
   var productsWithId3 = dbContext.Products
       .Where(product => product.Id == 3);
   var indicesOfProductsWithId3 = productsWithId3
       .Select(product => product.Index);
   // of course this can be done in one step

   // the query is not executed until you start enumerating
   foreach (var index in indicesOfProductsWithId3)
   {
       Console.WriteLine(index.ToString());
    }     
}

请务必在结束 using 语句之前枚举您的查询。你的编译器不会抱怨,但是你会在运行时得到一个异常

于 2017-01-05T13:54:44.683 回答