【问题标题】:Most efficent way to select a collection of objects from DbContext从 DbContext 中选择对象集合的最有效方法
【发布时间】:2014-02-14 13:31:07
【问题描述】:

在 MVC 中,如果我需要使用主键从数据库中获取一个对象,我可以使用 find 函数:

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);
}

大概每次调用Get都是一个数据库请求。

有没有像 Find 这样的功能,我可以只传递一组主键并取回一个集合?我没看到,写一个最好的方法是什么?

【问题讨论】:

  • ids 可以包含多少个元素?
  • 我预计不会超过几十个,但更多时候不会是单个数字。

标签: c# linq entity-framework asp.net-mvc-4 dbcontext


【解决方案1】:
DBContext db = new DBContext();
List<Guid> ids = ....

return db.Elements.Where(z => ids.Contains(z.Id));  // Use .ToList() to materialize entities

【讨论】:

    【解决方案2】:

    另一种方式是使用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();
    }
    

    【讨论】:

      【解决方案3】:

      为了获得最佳性能,您应该关闭更改跟踪(会有很大的不同)
      (从ken2k复制代码)

      DBContext db = new DBContext();
      List<Guid> ids = ....
      
      return db.Elements
          .AsNoTracking()
          .Where(z => ids.Contains(z.Id));  // Use .ToList() to materialize entities
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-20
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多