Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities projection of nested list

Assuming these objects...

class MyClass
{
     int ID {get;set;}
     string Name {get;set;}
     List<MyOtherClass> Things {get;set;}
}

class MyOtherClass
{
     int ID {get;set;}
     string Value {get;set;}
}

How do I perform a LINQ to Entities Query, using a projection like below, that will give me a List? This works fine with an IEnumerable (assuming MyClass.Things is an IEnumerable, but I need to use List)

MyClass myClass = (from MyClassTable mct in this.Context.MyClassTableSet
                        select new MyClass
                        {
                             ID = mct.ID,
                             Name = mct.Name,
                             Things = (from MyOtherClass moc in mct.Stuff
                                       where moc.IsActive
                                       select new MyOtherClass
                                       {
                                            ID = moc.ID,
                                            Value = moc.Value
                                       }).AsEnumerable()
                        }).FirstOrDefault();

Thanks in advance for the help!

like image 226
ctorx Avatar asked May 28 '10 16:05

ctorx


1 Answers

You don't. You have to do this part in L2O.

So you could do:

var q = (from MyClassTable mct in this.Context.MyClassTableSet
         select new // note anonymous type; important!
         {
             ID = mct.ID,
             Name = mct.Name,
             Things = (from MyOtherClass moc in mct.Stuff
                       where moc.IsActive
                       select new MyOtherClass
                       {
                           ID = moc.ID,
                           Value = moc.Value
                       }
          }).AsEnumerable();

MyClass myClass = (from mct in q
                   select new MyClass
                   {                 
                       ID = mct.ID,
                       Name = mct.Name,
                       Things = mct.Things.ToList()
                   }).FirstOrDefault();

There's no way to do this in one query.

like image 139
Craig Stuntz Avatar answered Oct 04 '22 11:10

Craig Stuntz