EF - Why Doesn't Include Work on Properties

So, I have classes that look like this.

public class User { public virtual IList<Member> Members {get;set;} } public class Member { public virtual AnotherTable Another {get;set;} } public class AnotherTable { public string Name {get;set;} } 

When I execute a query directly against the DataContext, Include works, but when I execute AsQueryable () for IList members, include does not work.

Is there a way to have Include / Eager functions for lazy loadable properties, like the Members property above, or do I always need to go through the DataContext to get this function?

 User.Members.AsQueryable().Include(a => a.Another).ToList() // <-- nada, no way Jose _db.Members.Include(m => m.Another).ToList() // <-- all good in the neighborhood 

I ask if this could be a huge difference in 1 sql query versus 100 queries for something equivalent result.

Thanks in advance.

+4
source share
3 answers

AsQueryable does not make a linq-to-entity query. This is a Linq-to-object query over List . List doesn't know how to handle Include - only DbQuery knows this, so you should get DbQuery :

 var entry = context.Entry(user); entry.Collection(u => u.Member).Query().Include(m => m.Another).Load(); 
+3
source

You will need to go through DbContext to work with Include (). You can abstract it in the repository, but you still need to pass the Include () expression to your base context.

  private IQueryable<T> GetQuery<T>(params Expression<Func<T, object>>[] includeProperties) where T : class { IQueryable<T> query = _db.Set<T>(); if (includeProperties != null) { foreach (Expression<Func<T, object>> expression in includeProperties) { query = query.Include(expression); } } return query; } 
0
source

I also had the same problem.

I decided this to simply add the System.Data.Entity link and use the following namespace:

  using System.Data.Entity; 

You can try.

-1
source

All Articles