一对一的反身关系 ef 核心



如何对一对一的反身关系进行建模。

我有这个模型,它可以是相同类型模型的父模型或子模型。把它想象成配偶关系。

同桌一对一。

我在想选项 1:

int? parentId;
int? childId;
modelBuilder.Entity<ENTITY>()
.HasOne(o => o.Parent)
.WithOne(a => a.Child)
.HasForeignKey<Document>(o => o.parentId)
modelBuilder.Entity<ENTITY>()
.HasOne(o => o.Child)
.WithOne(a => a.Parent)
.HasForeignKey<ENTITY>(o => o.childId) 

或选项 2:

int? relationId
bool parent
modelBuilder.Entity<ENTITY>()
.HasOne(o => o.Relation)
.WithOne(a => a.Relation)
.HasForeignKey<ENTITY>(o => o.relationId) 

我认为2º 选项是正确的。

modelBuilder.Entity<ENTITY>()
.HasOne<Relation>(e => e.Relation)
.WithOne(r => r.Entity)
.HasForeignKey<ENTITY>(r => r.relationId);

此链接可能很有用。 https://www.entityframeworktutorial.net/efcore/configure-one-to-one-relationship-using-fluent-api-in-ef-core.aspx 希望对您有所帮助!

最新更新