views:

27

answers:

2

That is, I want to do this:

var lists = (from list in this.DB.Lists
             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.

+1  A: 

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();
}
bendewey
+1, but... OMG, MICROSOFT! WHY MAGIC STRINGS!?!? WHY!?
John Gietzen
@John Gietzen, I know, it sucks... But you can use a lambda expression instead, see [this article](http://tomlev2.wordpress.com/2010/10/03/entity-framework-using-include-with-lambda-expressions/) for details
Thomas Levesque
@Thomas: Add that as an answer, and I will accept it.
John Gietzen
A: 

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();
Thomas Levesque