EFコアでの自己参照エラー:挿入ステートメントが外部キーの同じテーブル制約と競合しました

Aug 18 2020

Category自己参照のあるモデルがあり、データベースの作成に問題なく取り組んでいますが、親カテゴリ(parentIdのないエンティティ)を挿入しようとすると、外部キー「ParentId」を指すエラーが発生しますが、挿入すると問題なく機能します。 SSMSの挿入スクリプトを使用して手動でtopelし、サブカテゴリ(parentIdを持つエンティティ)を追加するときにefコアで正常に機能します

カテゴリモデル

public class Category : ICategory
{
    public Category()
    {
    }

    [Key]
    public int Id { get; set; }

    [Required]
    [MinLength(2)]
    [MaxLength(32)]
    public string Title { get; set; }

    public string Icon { get; set; }

    [DefaultValue(true)]
    public bool IsEnabled { get; set; }

    [Required]
    public DateTime CreateTimeStamp { get; set; }

    public DateTime LastUpdateTimeStamp { get; set; }

    [ForeignKey("User")]
    public int CreatorUserId { get; set; }
    
    public int? ParentId { get; set; }

    public virtual User User { get; set; }
    
    [ForeignKey("ParentId")]
    public virtual Category Parent { get; set; }
    public virtual ICollection<Category> Children { get; set; }
    public virtual ICollection<Service> Services { get; set; }
}

DBContext

public DbSet<Category> Categories { get; set; }

modelBuilder.Entity<Category>(entity =>
        {
            entity.HasIndex(e => e.Title).IsUnique();
            entity.HasOne(e => e.User).WithMany(e => e.CreatedCategories)
                .HasForeignKey(e => e.CreatorUserId).OnDelete(DeleteBehavior.Restrict);
            entity.HasOne(e => e.Parent).WithMany(e => e.Children).HasForeignKey(e => e.ParentId).IsRequired(false);
        });

移行

protected override void Up(MigrationBuilder migrationBuilder)
{
        migrationBuilder.CreateTable(
            name: "Categories",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Title = table.Column<string>(maxLength: 32, nullable: false),
                Photo = table.Column<string>(nullable: true),
                IsEnabled = table.Column<bool>(nullable: false),
                CreateTimeStamp = table.Column<DateTime>(nullable: false),
                LastUpdateTimeStamp = table.Column<DateTime>(nullable: false),
                CreatorUserId = table.Column<int>(nullable: false),
                ParentId = table.Column<int>(nullable: true)
            }
            constraints: table =>
            {
                table.PrimaryKey("PK_Categories", x => x.Id);
                table.ForeignKey(
                    name: "FK_Categories_Users_CreatorUserId",
                    column: x => x.CreatorUserId,
                    principalTable: "Users",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
                table.ForeignKey(
                    name: "FK_Categories_Categories_ParentId",
                    column: x => x.ParentId,
                    principalTable: "Categories",
                    principalColumn: "Id",
                    onDelete: ReferentialAction.Restrict);
            });
}

とにかく「ParentId」をnull許容とマークしましたが、SQL Serverは問題ありませんが、efコアが原因で問題が発生していません。

エラーメッセージの内部例外:

INSERTステートメントがFOREIGNKEY SAMETABLE制約「FK_Categories_Categories_ParentId」と競合しました。データベース「Unknown_Db」、テーブル「dbo.Categories」、列「Id」で競合が発生しました。

回答

1 happykratos Aug 18 2020 at 00:38

入力値を処理する場所でこれを試してください。

if (category.ParentId == 0)
{
    category.ParentId = null;
}