gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:50:30 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com