当存在 link table(和 class)时,如何加载 child 实体集合?

How do I load a child collection of entities when a link table (and class) exists?

我的 many-to-many 关系需要 link table(权重字段)中的有效负载数据。

public class Formula
{
    public int ID { get; set; }
    ...
    public virtual ICollection<FormulaComponent> FormulaComponents { get; set; }
}

public class Component
{
    public int ID { get; set; }
    ...
    public virtual ICollection<FormulaComponent> FormulaComponents { get; set; }
}

public class FormulaComponent
{
    [Key, Column(Order = 0)]
    public int FormulaID { get; set; }

    [Key, Column(Order = 1)]
    public int ComponentID { get; set; }

    [ForeignKey("FormulaID")]
    public virtual Formula Formula { get; set; }

    [ForeignKey("ComponentID")]
    public virtual Component Component { get; set; }

    public double? Weight { get; set; }
}

我正在努力研究如何使用 linq 为 parent 实体(特定公式的组件)加载 child 数据。我的代码在需要有效载荷数据之前就可以正常工作。当我没有 class 表示 link table 并且 child 是 parent (ICollection<Component>) 的 属性 时是我在断开连接的情况下加载 child 数据的方式:

_context.Entry(Formula).Collection(f => f.Components).Load();

因为 child 集合不再是 parent 的 属性 我试过这个:

_context.Entry(Formula).Collection(f => f.FormulaComponents).Load();

但是那只能得到linktable数据。由于组件是 link table 的 属性 我怀疑我需要添加一个 Select 或 Select 许多但我无法获得正确的语法:

_context.Entry(Formula).Collection(f => f.FormulaComponents.Select(???)).Load();

任何帮助将不胜感激。

抱歉,目前我无法测试该解决方案,但也许它会起作用。

_context.Entry(Formula).Collection(f => f.FormulaComponents).Load();
_context.Entry(Formula.FormulaComponents).Reference(fc => fc.Component).Load();

因为您有一个 多对多 关系(公式 - 组件)在您的关系 table 中有属性(FormulaComponent) 你实际上有一个 一对多 (Formula - FormulaComponent) 和一个多对一 (FormulaComponent - Component) 关系。 因此,您必须首先加载集合 (FormulaComponent),然后是集合中每个条目对 Component 的引用。

如果有效请告诉我。

我在这里回答我自己的问题。我没有意识到子组件实体是与 FormulaComponents 一起加载的。所以这行代码(在问题中)确实有效:

_context.Entry(Formula).Collection(f => f.FormulaComponents).Load();

所以当我说"But that only gets the link table data"时,我实际上错了。它加载的正是我想要加载的内容。