How to include 2 navigational properties in EF?

老子叫甜甜 提交于 2019-12-08 05:27:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!