I’m using EF4. Having 2 entities:
Person { Name }
Hobbys { Person.Name, IsCoolHobby }
1 Person can have several hobbys.
I now have
IQueryable<Person> p;
p = container.PersonSet.Include("Hobbys").AsQueryable();
p = p.Where(x => x ?????);
List<Person> tmp = p.ToList();
How can i return only those Persons who have cool hobbys (IsCoolHobby == true)? I tried join but i was not able to load them into the list (select can only return Person, Hobby or new Type – but how to map them to entity objects again?)
Thanks
This will load the people who have at least one cool hobby but the
Hobbyscollection for those people will always contain all hobbys, also the uncool hobbys.Edit
Unfortunately filtering and sorting children during eager loading (
Include) is currently not supported. There is a request on the EF feature suggestion page for this feature. The request has status “Under review”, so there is a little hope that it might get implemented in the future. (Probably far future: At least the first docs about EF 5 (beta) on MSDN say explicitly that eager loading with filtering/sorting is still not implemented.)For now there are only two workarounds. The first is to use a projection:
The result is a collection of anonymous objects which contain a user who has cool hobbys and a collection of those cool hobbys. If you don’t disable change tracking (by using the
NoTrackingoption for the query) the person’s hobbys collection should be filled with the result automatically.The second option is to use “explicit” loading with
CreateSourceQuery:Two things to note here:
CreateSourceQueryis only available onEntityCollections, i.e. if you are usingEntityObjectderived entities. It’s not available for POCO entities in EF 4.0. (EF >= 4.1/DbContexthas the option for explicit loading also for POCOs ->Query()method.)