问题
An object in my database has 2 navigational properties (B and C):
Object A
{
B bProperty
C cProperty
}
I wish to include them both when querying object A. I tried doing the following:
dbcontext.A.Include(x => x.B).ToList();
But how do I include C too?
回答1:
Try this
dbcontext.A.Include(x => x.B).Include(x => x.C).ToList();
I do it all in one go, so in my EF repository class, I have a method called GetAllIncluding which equals do it in a generic way for each entity,
public IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] includes)
{
var query = DbSet.AsNoTracking();
query = includes.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));
return query;
}
where DbSet is a private member of type IDbSet and T is a of type BaseEntity.
and the way I use it is like this
MyGenericRepository<A>().GetAllIncluding(x=> x.B, x=> x.C).FirstOrDefault();
Hope that helps.
来源:https://stackoverflow.com/questions/26619532/how-to-include-2-navigational-properties-in-ef