[英]Self referencing / parent-child relationship one-to-zero or one in Entity Framework Core
I want to create a referencing / parent-child relationship one-to-zero or one in Entity Framework Core.我想在 Entity Framework Core 中创建一对零或一对的引用/父子关系。 I mean that my entity could have a parent:
我的意思是我的实体可能有一个父母:
public class MyEntity
{
public Guid Id { get; set; }
public Guid? ParentEntityId { get; set; }
public MyEntity ParentEntity { get; set; }
public MyEntity ChildEntity { get; set; }
}
I am trying to configure it via fluent api:我正在尝试通过流利的 api 对其进行配置:
entity.HasOne(x => x.ParentEntity)
.WithOne(x => x.ChildEntity)
.HasForeignKey( .... )
I do not understand what I do have to write in the last line.我不明白我必须在最后一行写什么。 I am not either sure my entity is correct.
我也不确定我的实体是否正确。
Can anyone help me please?任何人都可以帮助我吗?
EDIT : This question does not resolve my problem: Self referencing / parent-child relationship in Entity Framework My problem is about create the foreign key.编辑:这个问题不能解决我的问题: 实体框架中的自引用/父子关系我的问题是关于创建外键。 This line does not work:
此行不起作用:
.HasForeignKey(x => x.ParentEntityId)
HasForeignKey
expects a string in input. HasForeignKey
需要输入字符串。
In a one-to-one relationship you always have to specify the dependent entity type in the HasForeignKey
call, ie the entity that will contain the foreign key.在一对一的关系中,您始终必须在
HasForeignKey
调用中指定依赖实体类型,即包含外键的实体。 For a one-to-one relationship between two different classes that makes sense, see the standard EF example .有关两个不同类之间有意义的一对一关系,请参阅标准 EF 示例。 For a self-reference it looks obvious that EF should figure out there's no option.
对于自我参考,显然 EF 应该弄清楚没有选择。 Still, you have to specify the type:
不过,您必须指定类型:
modelBuilder.Entity<MyEntity>()
.HasOne(x => x.ParentEntity)
.WithOne(x => x.ChildEntity)
.HasForeignKey<MyEntity>(c => c.ParentEntityId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.