I have a Category model with self-reference and worked fine on creating database yet when I try to insert a parent category (an entity without parentId) I get the error pointing to the foreign-key "ParentId", but it works fine when I insert a topel manually with insert script in SSMS and works fine with ef core when adding a subcategory (an entity which has a parentId)
Category Model
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);
});
Migration
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);
});
}
I marked "ParentId" nullable anyway I could yet ef core is preventing me though the SQL Server is fine with it!
Error message inner exception:
The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Categories_Categories_ParentId". The conflict occurred in database "Unknown_Db", table "dbo.Categories", column 'Id'.