Auto-referência no EF Core Erro: a instrução insert entrou em conflito com a mesma restrição da tabela de chave estrangeira

Aug 18 2020

Eu tenho um Categorymodelo com auto-referência e funcionou bem na criação de banco de dados, mas quando tento inserir uma categoria pai (uma entidade sem parentId), recebo o erro apontando para a chave estrangeira "ParentId", mas funciona bem quando insiro um topel manualmente com inserir script em SSMS e funciona bem com ef core ao adicionar uma subcategoria (uma entidade que tem um parentId)

Modelo de Categoria

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);
        });

Migração

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);
            });
}

Marquei "ParentId" como anulável de qualquer maneira, mas o ef core está me impedindo, embora o SQL Server esteja bem com isso!

Exceção interna da mensagem de erro:

A instrução INSERT entrou em conflito com a restrição FOREIGN KEY SAME TABLE "FK_Categories_Categories_ParentId". O conflito ocorreu na base de dados "Unknown_Db", tabela "dbo.Categories", coluna 'Id'.

Respostas

1 happykratos Aug 18 2020 at 00:38

Tente aqui onde você lida com valores de entrada:

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