【发布时间】:2017-03-21 00:37:27
【问题描述】:
我有一个类,Relationship,它有一个 InverseRelationship 属性。任何给定的关系总是有一个 InverseRelationship,它也是一个关系。
我的班级现在是这样的:
public class Relationship
{
#region Constructor
public Relationship()
{
}
#endregion Constructor
#region Properties
[Key]
[Required]
public int Id { get; set; }
[Required]
public string Description { get; set; }
public int? InverseRelationshipId { get; set; }
#endregion Properties
#region Related Properties
[ForeignKey("InverseRelationshipId")]
public virtual Relationship InverseRelationship { get; set; }
#endregion Related Properties
}
当我尝试填充表格时,我收到一条消息说
Unable to save changes because a circular dependency was detected in the data to be saved
然后我尝试使用 Fluent API 来执行此操作,结果如下:
modelBuilder.Entity<Relationship>()
.HasOne(r => r.InverseRelationship)
.WithOne(r => r.InverseRelationship)
.HasForeignKey<Relationship>(r => r.InverseRelationshipId)
.IsRequired(false);
当我尝试创建迁移时,我得到以下信息:
The navigation property 'InverseRelationship' cannot be added to the entity type 'Relationship' because a navigation property with the same name already exists on entity type 'Relationship'.
这是有道理的,但我不知道如何绕过它。我不知道如何才能实现我在这里的目标。
更新 这是我用来实际填充表格的代码(在尝试使用模型构建器代码之前)。
EntityEntry<Relationship> rel1 = DbContext.Relationships.Add(new Relationship()
{
UserId = authorId,
Title = "Relationship 1",
Description = "Relationship 1",
CreatedDate = createdDate,
LastModifiedDate = lastModifiedDate
});
EntityEntry<Relationship> rel2 = DbContext.Relationships.Add(new Relationship()
{
UserId = authorId,
Title = "Relationship 2",
Description = "Relationship 2",
CreatedDate = createdDate,
LastModifiedDate = lastModifiedDate,
InverseRelationship = rel1.Entity
});
EntityEntry<Relationship> rel3 = DbContext.Relationships.Add(new Relationship()
{
UserId = authorId,
Title = "Relationship 3",
Description = "Relationship 3",
CreatedDate = createdDate,
LastModifiedDate = lastModifiedDate
});
EntityEntry<Relationship> rel4 = DbContext.Relationships.Add(new Relationship()
{
UserId = authorId,
Title = "Relationship 4",
Description = "Relationship 4",
CreatedDate = createdDate,
LastModifiedDate = lastModifiedDate,
InverseRelationship = rel3.Entity
});
rel1.Entity.InverseRelationship = rel2.Entity;
rel3.Entity.InverseRelationship = rel4.Entity;
DbContext.SaveChanges();
【问题讨论】:
-
这里的讨论和建议可能有用:github.com/aspnet/EntityFramework/issues/3376
-
你能发布代码吗?你是如何保存实体的?
-
@Smit 我将它添加到原始帖子中。我没有考虑到问题可能出在哪里,但现在你提到它可能是有道理的。
标签: c# entity-framework ef-code-first entity-framework-core