0

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?

Jim
  • 14,952
  • 15
  • 80
  • 167
  • http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx – Jim May 10 '12 at 05:28

1 Answers1

0

Filtering and sorting with eager loading is not supported. The only way to load the data in a single roundtrip is a projection:

var peopleWithRole = (from p in Party
                      select new
                      {
                          Party = p,
                          Roles = p.Roles.Where(r => r.RoleTypeId == 1)
                      })
                      .ToList()
                      .Select(a => a.Party);

If the relationship is one-to-many EF ("relationship fixup") will populate the filtered Roles collection automatically in each Party (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.

Slauma
  • 175,098
  • 59
  • 401
  • 420
  • I came to this conclusion eventually. Thanks for confirming it. I do hope they add the feature. – Jim Apr 23 '12 at 04:45
  • This might help, looks like you actually can do it now. I will test it to confirm, I have just found this link. http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx – Jim May 10 '12 at 05:29
  • @Jim: No, the filtering is only possible with *explicit loading* (=two DB queries), not with eager loading. Filtering with eager loading is even not available in EF 5 (beta), we still have to wait... – Slauma May 10 '12 at 09:01
  • You are correct, let's hope they add it. The Entity(?).Collection load example is not what we actually require. It must work with full linq query semantics and limit the navigation as it should. – Jim May 11 '12 at 12:31