How to include 2 navigational properties in EF?

2019-06-02 09:16发布

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条回答
神经病院院长
2楼-- · 2019-06-02 09:40

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.

查看更多
登录 后发表回答