调用 SaveChangesAsync 时出现异常。 我的架构非常简单,我有一个类别类,其中包含
public class Category {
public Guid ID {get; set;}
public Guid? ParentId {get; set;}
public Category Parent {get; set;}
[...]
}
当我想在数据库中插入一个新类别(连接到我的 ASP MVC 应用程序)时,我在执行插入之前设置了 GUID。 当我的数据库为空并且我想插入父类别时发生错误(因此 Guid IdParent 和 Parent 为空)。如果我设置父值,则不会发生这种情况。我可以通过 Visual Studio 将 parent 设置为 Null 来手动添加记录。
我有以下错误:
The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Category_Category_ParentId". The conflict occurred in database "HT_Root", table "dbo.Category", column 'ID'. The statement has been terminated.
我在堆栈溢出上搜索了一个简单的答案,但没有找到。 我尝试使用 Fluent API:
modelBuilder.Entity<Category>().HasOne(s => s.Parent).WithMany().HasForeignKey(s => s.ParentId);
但是什么都没有改变。我做错了什么?
最佳答案
它似乎在 EF 7 中发生了变化 See this github issue
尝试
public class Category
{
public Guid ID {get; set;}
public Guid? ParentId {get; set;}
public Category Parent {get; set;}
public ICollection<Categories> Children {get; set;}
}
和
modelBuilder.Entity<Category>()
.HasOne(x => x.Parent)
.WithMany(x => x.Children)
.HasForeignKey(x => x.ParentId)
.Required(false);
您还应该始终检查(如果已指定)ParentId 是否存在于数据库中。注意添加 Guid.Empty
(00000000-0000-0000-0000-000000000000) 而不是 null
,因为这可能会导致问题。
关于c# - EF 7 : INSERT statement conflicted with the FOREIGN KEY SAME TABLE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34996155/