c# - EF 7 : INSERT statement conflicted with the FOREIGN KEY SAME TABLE

标签 c# sql-server asp.net-mvc entity-framework entity-framework-core

调用 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/

相关文章:

javascript - asp.net mvc 从 Html.TextBoxFor() 获取值

c# - 如何在 MathNet 中找到最大矩阵元素?

c# - 将 "Please Select"添加到从数据库中检索值的下拉列表

c# - 动态数据的正确数据类型?

sql-server - 使用巨大的 IN 语句帮助优化此查询

sql - 两列上的 group by 索引

javascript - 使用 Jquery 检查 MVC 模型属性是否为 null

c# - 为什么我不能两次读取 Http Request Input 流?

c# - 同步多套接字客户端说明

sql - 如何将 OLE 自动化日期值转换为 SQL Server 中的日期