[英]Entity Framework Core : Access parent from child
可能是一个愚蠢的问题,但我在这里有点困惑。
我有一个包含孩子列表的父实体。
public class Parent
{
public int Id { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
}
EFcore将在表Child
创建ParentId
作为外键。
现在,假设我要检索具有特定父级的所有子级,该怎么办? ParentId
在Child
对象中不可用。
因此,我无法执行以下操作:
var result = model.Child.Where(child => child.ParentId == 3);
我可以将ParentId
属性添加到实体中的子级,但是我真的不希望手动分配此属性。 如果仅通过指定getter将其设置为readonly,则迁移将不再起作用。
EF Core允许您使用EF.Property方法访问LINQ to Entities查询中的关联阴影属性 :
解决实体实例上的给定属性。 当您要在LINQ查询中引用阴影状态属性时,此功能很有用。 当前,此方法只能在LINQ查询中使用,不能在其他情况下用于访问分配给属性的值。
您只需要知道名称和类型-在您的情况下,它们是“ ParentId”和int?
(可选的):
var result = model.Child.Where(child => EF.Property<int?>(child, "ParentId") == 3);
我建议您在@ScotG答案中提供的各个类中都具有引用(儿童父母和父母子女)。
但是,由于您不希望这样做,因此在使用延迟加载的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.