There is a table in the database, it has a tree of objects. When I try to add a record it gives out "violation of foreign key constraints". When you add manually, everything is fine.
Part of the model
public int? ParentId { get; set; }
public Good Parent { get; set; }
public virtual ICollection<Good> LinkedGoods { get; set; }
builder.Entity<Good>().HasOne(x => x.Parent).WithMany(x => x.LinkedGoods).HasForeignKey(x => x.ParentId).OnDelete(DeleteBehavior.SetNull);
First I create the main object, save it and pass here its Id and the number of child products
private async Task<OkResult> CreateLinkedItems(int parentId,int linkQuantity)
{
var good = await _db.Goods.FindAsync(parentId);
good.Id = 0;
for (int i = 0; i < linkQuantity; i++)
{
(var code, var number) = GetCode(good.CategoryId, good.HasDefects);
good.Code = code;
good.Number = number;
good.ParentId = good.Id;
_db.Goods.Add(good);
_db.SaveChanges();
}
return Ok();
}
P.S Checked the data manually, the error is in ParentId