如何在多对多的关系中得到急切的加载? [英] how to get eager loading in a many to many relationships?

查看:114
本文介绍了如何在多对多的关系中得到急切的加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有四个表的数据库。 TableA和TableB是主表,TableC是多对多关系的表。




  • TableA(IDTableA,Name ... )

  • TableB(IDTableB,Name ...)

  • TableC(IDTableA,IDTableB)



这创建了三个实体,EntityA有一个Entity C的ICollection,实体C有一个EntitiesB的集合,所以当我尝试获取相关的实体时,我这样做:

  myContext.EntityA.Include(a => a.EntityB.Select(b => b.EntityC)); 

但是这个throw和异常说明集合为null。



所以我想知道是否可以做一个急切的加载,当有一个表,多对多的关系。



谢谢。

解决方案

在Entity Framework中有许多关联,你可以在两种实现之间进行选择:




  • 连接表(C)是概念模型(类模型)的一部分,关联是 A-C-B (1-n-1)。

  • 联结表不是概念模型的一部分,但Entity Framework透明地使用它来维持关联 A-B (n-m)。 A具有B的集合,B具有As的集合。这只有在表C只包含两个FK列到A和B时才可能。



/ p>

你(显然)选择了第一个选项,所以你总是必须通过 C 查询其他的

  from a in context.As 
select new {a,Bs = a.Cs.Select(c => ; cB)}



<$ p $ (a => a1.Cs.Select(c => cB))


I have a database with four tables. TableA and TableB are the main tables and the TableC is the table of the many to many relationships.

  • TableA(IDTableA, Name...)
  • TableB(IDTableB, Name...)
  • TableC(IDTableA, IDTableB)

This create three entities, The EntityA has an ICollection of Entity C and Entity C has a Collection of EntitiesB, so when I try to get the related entities I do this:

myContext.EntityA.Include(a=>a.EntityB.Select(b=>b.EntityC));

But this throw and exception that says that the collection is null.

So I would like to know if it is possible to do an eager loading when there are a table for the many to many relationship.

Thanks.

解决方案

With many to many association in Entity Framework you can choose between two implementations:

  • The junction table (C) is part of the conceptual model (class model) and the associations are A—C—B (1—n—1). A can't have a collection of Bs.
  • The junction table is not part of the conceptual model, but Entity Framework uses it transparently to sustain the association A—B (n—m). A has a collection of Bs and B has a collection of As. This is only possible when table C only contains the two FK columns to A and B.

So you can't have both.

You (apparently) chose the first option, so you will always have to query the other entites through C, like

from a in context.As
select new { a, Bs = a.Cs.Select(c => c.B) }

or

from a in As.Include(a1 => a1.Cs.Select(c => c.B))

这篇关于如何在多对多的关系中得到急切的加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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