Is it possible using DbContext / DbSet / DbQuery to conditionally eagerly load a navigation property. The query below will return parties that have a particular role.
What I need is to additionally only load the matching roles.
first attempt
var peopleWithRole = (from p in Party
from r in p.Roles
where r.RoleTypeId == 1
select p).Include(_ => _.Roles);
This loads all the roles, and it’s obvious why once you look at it.
I have tried a few things. If I have to cast and create an objectquery to do it that would be fine, I just can’t figure out how.
second attempt
var objectContext = ((IObjectContextAdapter)this).ObjectContext;
var set = objectContext.CreateObjectSet<Party>();
var result = (from p in set.Where("it.Roles.RoleTypeId == 1")
select p)
;
result.Dump();
The iterator cannot be used like this?
Any ideas?
Filtering and sorting with eager loading is not supported. The only way to load the data in a single roundtrip is a projection:
If the relationship is one-to-many EF (“relationship fixup”) will populate the filtered
Rolescollection automatically in eachParty(if you don’t disable change tracking). If the relationship is many-to-many it doesn’t work that easy and you need to fill the collections manually after you have returned the result list of anonymous objects.Last option is to vote for the eager loading filtering feature here: http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015345-allow-filtering-for-include-extension-method … and hope it will be implemented in future EF releases.