如何在EF中包含2个导航属性? [英] How to include 2 navigational properties in EF?

查看:820
本文介绍了如何在EF中包含2个导航属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中的一个对象有两个导航属性(B和C):

An object in my database has 2 navigational properties (B and C):

Object A
{
  B bProperty

  C cProperty
}

我希望在查询对象A时包含它们。
我尝试执行以下操作:

I wish to include them both when querying object A. I tried doing the following:

dbcontext.A.Include(x => x.B).ToList();

但是如何包括C?

推荐答案

尝试这个

dbcontext.A.Include(x => xB).Include(x => xC) ();

dbcontext.A.Include(x => x.B).Include(x => x.C).ToList();

我一直都这样做,所以在我的EF存储库类中,我有一个叫GetAllIncluding的方法,它等于以每个实体的通用方式,

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;
}

其中DbSet是IDbSet类型的私有成员,T是BaseEntity类型

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();

希望有所帮助。

这篇关于如何在EF中包含2个导航属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆