如何首先在实体框架代码中从表的主键生成两个外键
本文关键字:两个 实体 何首先 框架 代码 | 更新日期: 2023-09-27 18:05:06
我的场景是,我有两个名为Person和RelationshipMappings的表。在Person表中,PersonId是主键。在RelationshipMappings表中,有两个整数LeftPersonId和RightPersonId。这两个id都应该是PersonId的外键。
我在Relationship模型中创建了两个Person属性,分别是LeftPerson和RightPerson,然后创建了如下所示的表关系。
entityBuilder
.HasOne(r => r.LeftPerson)
.WithMany(r => r.RelationshipMappings)
.HasForeignKey(r => r.LeftPersonId)
.HasConstraintName("FK_RelationshipMapping_LeftPerson");
entityBuilder
.HasOne(r => r.RightPerson)
.WithMany(r => r.RelationshipMappings)
.HasForeignKey(r => r.RightPersonId)
.HasConstraintName("FK_RelationshipMapping_RightPerson");
我应该有两个集合在人模型(LeftPerson和RightPerson)?因为现在我在PersonModel中只有一个集合。
public ICollection<RelationshipMapping> RelationshipMappings { get; set; }
我也有PersonModel中提到的关系。
entityBuilder
.HasMany(e => e.RelationshipMappings)
.WithOne(e => e.LeftPerson);
entityBuilder
.HasMany(e => e.RelationshipMappings)
.WithOne(e => e.RightPerson);
它不工作的原因。它无法创建表和之后的所有内容。我看不出例外。我正在努力找出答案。
有人能帮我一下吗?好了,我找到解决方案了。我必须在外键中添加删除行为。
entityBuilder
.HasOne(r => r.LeftPerson)
.WithMany(r => r.LeftRelationshipMappings)
.HasForeignKey(r => r.LeftPersonId)
.HasConstraintName("FK_RelationshipMapping_LeftPerson")
.OnDelete(DeleteBehavior.Restrict);
entityBuilder
.HasOne(r => r.RightPerson)
.WithMany(r => r.RightRelationshipMappings)
.HasForeignKey(r => r.RightPersonId)
.HasConstraintName("FK_RelationshipMapping_RightPerson")
.OnDelete(DeleteBehavior.Restrict);
现在一切正常。不过我得有两个系列。它不适用于一个集合。它会给出下面的误差。
Cannot create a relationship between 'Person.RelationshipMappings' and 'RelationshipMapping.RightPerson', because there already is a relationship between 'Person.RelationshipMappings' and 'RelationshipMapping.LeftPerson'. Navigation properties can only participate in a single relationship.
谢谢你的评论