简体   繁体   English

实体框架核心:从子级访问父级

[英]Entity Framework Core : Access parent from child

Might be a silly question but I'm a bit confused here. 可能是一个愚蠢的问题,但我在这里有点困惑。

I have a parent entity which contains a list of children. 我有一个包含孩子列表的父实体。

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

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

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

EFcore will create a ParentId as a foreign key in the table Child . EFcore将在表Child创建ParentId作为外键。

Now, let's say I want to retrieve all the children that have a specific Parent, how should I do it ? 现在,假设我要检索具有特定父级的所有子级,该怎么办? The ParentId is not available in the Child object. ParentIdChild对象中不可用。

Therefore, I cannot do something like: 因此,我无法执行以下操作:

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

I could add the ParentId property to the child in the entity, but I really don't want this property to be assigned manually. 我可以将ParentId属性添加到实体中的子级,但是我真的不希望手动分配此属性。 And if I set it as readonly by specifying the getter only, the migration doesn't work anymore. 如果仅通过指定getter将其设置为readonly,则迁移将不再起作用。

EF Core allows you to access the associated shadow property in LINQ to Entities query using the EF.Property method: EF Core允许您使用EF.Property方法访问LINQ to Entities查询中的关联阴影属性

Addresses a given property on an entity instance. 解决实体实例上的给定属性。 This is useful when you want to reference a shadow state property in a LINQ query. 当您要在LINQ查询中引用阴影状态属性时,此功能很有用。 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. 当前,此方法只能在LINQ查询中使用,不能在其他情况下用于访问分配给属性的值。

All you need to know is the name and the type - in your case they are "ParentId" and int? 您只需要知道名称和类型-在您的情况下,它们是“ ParentId”和int? (optional): (可选的):

var result = model.Child.Where(child => EF.Property<int?>(child, "ParentId") == 3);

I would recommend you have both the references (child-parent and parent-children) in the respective classes as provided in @ScotG answer. 我建议您在@ScotG答案中提供的各个类中都具有引用(儿童父母和父母子女)。

However,since you dont want that, in EF using lazy loading you can do something like model.Parents.Find(3).Children since from the Parent class you have the references of its children. 但是,由于您不希望这样做,因此在使用延迟加载的EF中,您可以执行诸如model.Parents.Find(3).Children之类的操作,因为从Parent类中可以获取其子级的引用。

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 https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM