C# 从DbContext中选择对象集合的最有效方法
在MVC中,如果我需要使用主键从数据库中获取一个对象,我可以使用find函数:C# 从DbContext中选择对象集合的最有效方法,c#,linq,entity-framework,asp.net-mvc-4,dbcontext,C#,Linq,Entity Framework,Asp.net Mvc 4,Dbcontext,在MVC中,如果我需要使用主键从数据库中获取一个对象,我可以使用find函数: public static Element List(Guid id) { DBContext db = new DBContext(); return db.Elements.Find(id); } 获取对象集合的最有效方法是什么 这似乎不是很有效,尽管它会起作用: public static IEnumerable<Element> List(IEnumerable<Guid&
public static Element List(Guid id)
{
DBContext db = new DBContext();
return db.Elements.Find(id);
}
获取对象集合的最有效方法是什么
这似乎不是很有效,尽管它会起作用:
public static IEnumerable<Element> List(IEnumerable<Guid> ids)
{
foreach (Guid id in ids)
yield return Get(id);
}
公共静态IEnumerable列表(IEnumerable ID)
{
foreach(id中的Guid id)
收益率-收益率(id);
}
可能每个Get调用都是一个数据库请求
有没有一个像Find这样的函数,我可以直接交给一组主键,然后取回一组主键?我没有看到,写一个的最好方法是什么?DBContext db=newdbcontext();
DBContext db = new DBContext();
List<Guid> ids = ....
return db.Elements.Where(z => ids.Contains(z.Id)); // Use .ToList() to materialize entities
列表ID=。。。。
返回db.Elements.Where(z=>ids.Contains(z.Id));//使用.ToList()来具体化实体
另一种方法是使用Linq:
List<Guid> your_ids = ..... ;
using(DBContext db = new DBcontext())
{
var lst = from e in db.Elements
where your_ids.Contains(e.Id)
select e;
List<Guid> result_list = lst.ToList();
}
列出您的_id=;
使用(DBContext db=new DBContext())
{
var lst=从e开始,单位为db.Elements
您的_Id.包含的位置(e.Id)
选择e;
列表结果_List=lst.ToList();
}
为了获得最佳性能,您应该关闭更改跟踪(产生巨大差异)(从ken2k复制的代码)
DBContext db=newdbcontext();
列表ID=。。。。
返回db.Elements
.AsNoTracking()
。其中(z=>ids.Contains(z.Id));//使用.ToList()来具体化实体
idid可以包含多少个元素?我预计不会超过几十个元素,但通常情况下都是单个数字。
DBContext db = new DBContext();
List<Guid> ids = ....
return db.Elements
.AsNoTracking()
.Where(z => ids.Contains(z.Id)); // Use .ToList() to materialize entities