Entity Framework 核心:从 child 访问 parent

Entity Framework Core : Access parent from child

可能是个愚蠢的问题,但我在这里有点困惑。

我有一个 parent 实体,其中包含 children 的列表。

public class Parent
{
    public int Id { get; set; }

    public List<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
}

EFcore 将在 table Child.

中创建一个 ParentId 作为外键

现在,假设我想检索所有具有特定 Parent 的 children,我应该怎么做? ParentIdChild object 中不可用。

因此,我不能做类似的事情:

var result = model.Child.Where(child => child.ParentId == 3);

我可以将 ParentId 属性 添加到实体中的 child,但我真的不希望手动分配此 属性。如果我通过仅指定 getter 将其设置为只读,迁移将不再有效。

EF Core 允许您访问关联的 shadow property in LINQ to Entities query using the EF.Property 方法:

Addresses a given property on an entity instance. This is useful when you want to reference a shadow state property in a LINQ query. Currently this method can only be used in LINQ queries and can not be used to access the value assigned to a property in other scenarios.

您只需要知道名称和类型 - 在您的情况下,它们是 "ParentId" 和 int?(可选):

var result = model.Child.Where(child => EF.Property<int?>(child, "ParentId") == 3);
public class Child
{
    public int Id { get; set; }

    // add these navigation properties to access the Parent
    public int ParentId {get; set; }
    public Parent Parent {get; set; }
}

https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship

我建议您在@ScotG 回答中提供的相应 classes 中同时引用(child-parent 和 parent-children)。

但是,由于您不希望这样做,因此在使用延迟加载的 EF 中,您可以执行类似 model.Parents.Find(3).Children 的操作,因为从父 class 中您拥有其子项的引用。