开发者

How can I get an IList of entites and their child objects in Entity Framework efficiently?

That is, I want to do this:

var lists = (from list in this.DB.Lists
            开发者_StackOverflow社区 select new
             {
                 List = list,
                 Items = list.ListItems.ToList(),
             }).ToList();

But, obviously, the Entity Framework doesn't support the ToList extension method in the select clause.

What should I do? Any other method I've tried ends up sending a ton of queries to the database when iterating.


Have you tried the Include etension method?

var lists = (from list in this.DB.Lists.Include("ListItems")
             select list).ToList(); 

foreach(var item in lists)
{
   // there shouldn't be any DB calls here.
   var items = list.ListItems.ToList();
}


You can't call ToList on the part of the query that is translated to SQL, but you can do it locally, using AsEnumerable:

var lists = (from list in this.DB.Lists.AsEnumerable()
             select new
             {
                 List = list,
                 Items = list.ListItemsItems.ToList()
             }).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜