如何在Entity Framework中使用Include()加载两个关联实体?
如何在Entity Framework中使用Include()加载两个关联实体?
嗨,我来帮你搞定这个问题!在Entity Framework里要一次性加载多个关联实体其实超简单,咱们直接用链式调用Include()方法就行——刚好你的CustomerSupplier实体里的Customer和CustomerAddress都是平级的直接关联,完全适用这种方式。
举个具体的例子,如果你想加载CustomerSupplier的同时,把对应的Customer和CustomerAddress也一起查出来,可以这么写:
// 假设你的DbContext实例叫context var customerSuppliers = context.CustomerSuppliers .Include(cs => cs.Customer) // 加载关联的Customer实体 .Include(cs => cs.CustomerAddress) // 加载关联的CustomerAddress实体 .ToList();
这种强类型的lambda写法特别推荐,因为编译的时候就能检查导航属性名有没有写错,比EF6里的字符串重载靠谱多啦。
要是之后你还想加载其他关联,比如Supplier,直接继续追加Include()就行:
var customerSuppliers = context.CustomerSuppliers .Include(cs => cs.Customer) .Include(cs => cs.CustomerAddress) .Include(cs => cs.Supplier) .ToList();
另外补充个小知识点:如果遇到嵌套关联(比如Customer本身还有一个子导航属性,比如CustomerContact),那就要用ThenInclude()来链式加载嵌套的实体,比如:
var customerSuppliers = context.CustomerSuppliers .Include(cs => cs.Customer) .ThenInclude(c => c.CustomerContact) // 加载Customer下的CustomerContact .Include(cs => cs.CustomerAddress) .ToList();
这样写就能一次性把所有需要的关联数据都加载完成,避免了延迟加载导致的多次数据库查询(也就是常说的N+1问题)。
备注:内容来源于stack exchange,提问作者GrasM4n
相关产品推荐
相关产品推荐

