【问题标题】:INSERT statement conflicted with FOREIGN KEY SAME TABLE constraint errorINSERT 语句与 FOREIGN KEY SAME TABLE 约束错误冲突
【发布时间】:2021-07-18 08:06:56
【问题描述】:

添加没有父类的新类别时会发生此错误。我试过类似问题的答案,但没有结果。

型号

public class Category
{
    [Column("CategoryId")]
    public Guid Id { get; set; }
    [Required(ErrorMessage = "Category name is a required field.")]
    [MinLength(1, ErrorMessage = "Minimum length for the Name is 1 characters.")]
    public string Name { get; set; }
    [ForeignKey("ParentId")]
    public Guid? ParentId { get; set; }
    public virtual Category Parent { get; set; }
    public virtual ICollection<Category> Children { get; set; }

}

请求

public class CategoryCreationDto
{
    public Guid ParentId { get; set; }
    public string Name { get; set; }
}

存储库

public void Create(T entity) => RepositoryContext.Set<T>().Add(entity); 
public void CreateCategory(Category category) => Create(category);

控制器

 Category categoryEntity = _mapper.Map<Category>(category);
        _repository.Category.CreateCategory(categoryEntity);
        await _repository.SaveAsync();

实体框架生成的表格

【问题讨论】:

  • 顺便说一句,您的数据库设计不会阻止引用循环。
  • 有问题吗?
  • 无法测试,但在同一属性上将属性更改为[ForeignKey("Parent")]将属性按原样移动到 Parent 属性对我来说更有意义。
  • 您显示的代码基本上是一个黑盒子。我们看不到 category/categoryEntity 中的内容。
  • 你在哪里为CategoryId分配一个唯一值?

标签: c# entity-framework asp.net-core .net-core entity-framework-core


【解决方案1】:

它与您的实体关系相关。

看这个例子:

存在问题 - 当一个实体不能与另一个实体存在时。 如果没有CustomerProduct,您就无法获得Order

您需要先为 *CustomerProduct 插入记录以添加 Product


在您的具体情况下:

首先将它们添加到数据库中:

 public Guid? ParentId { get; set; }
    public virtual Category Parent { get; set; }
    public virtual ICollection<Category> Children { get; set; }

添加类别


对于可选外键:

modelBuilder.Entity<Category>()
    .HasOptional(p => p.Parent)
    .WithMany()
    .HasForeignKey(p => p.ParentId);

【讨论】:

  • 我需要添加没有父级的类别。父属性是可选的
  • 好的-那么在映射关系时-需要添加可选的外键(编辑答案)
  • 仅作记录 - ef core ModelBuilder 没有 .HasOptional
  • @PiotrŻak EF 核心被称为 EF7
【解决方案2】:

您必须添加 fluent api(在此之后重复 db 迁移)

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
  modelBuilder.Entity<Category>()
            .HasOne(s => s.Parent)
            .WithMany(m => m.Children)
            .HasForeignKey(e => e.ParentId);

 OnModelCreatingPartial(modelBuilder);
 }

很抱歉,由于您没有发布您的映射器在做什么以及类别内的内容,我将发布整个测试代码(在 VS 中测试过)

        var categoryEntity = new Category {Id=new Guid(), Name="CategoryName"};
        context.Set<Category>().Add(categoryEntity ); 
        await context.SaveChangesAsync();

【讨论】:

    猜你喜欢
    • 2014-09-08
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多