Autoreferenziazione in EF core Errore: l'istruzione di inserimento era in conflitto con il vincolo della stessa tabella della chiave esterna

Aug 18 2020

Ho un Categorymodello con autoreferenzialità e ho lavorato bene sulla creazione del database, ma quando provo a inserire una categoria padre (un'entità senza parentId) ottengo l'errore che punta alla chiave esterna "ParentId", ma funziona bene quando inserisco un topel manualmente con script di inserimento in SSMS e funziona bene con ef core quando si aggiunge una sottocategoria (un'entità che ha un parentId)

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

Migrazione

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

Ho contrassegnato "ParentId" nullable comunque, potrei ancora ef core mi sta impedendo anche se SQL Server va bene!

Eccezione interna del messaggio di errore:

L'istruzione INSERT era in conflitto con il vincolo FOREIGN KEY SAME TABLE "FK_Categories_Categories_ParentId". Il conflitto si è verificato nel database "Unknown_Db", tabella "dbo.Categories", colonna "Id".

Risposte

1 happykratos Aug 18 2020 at 00:38

Prova questo dove gestisci i valori di input:

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