Answer the question
In order to leave comments, you need to log in
Where is the foreign key violation?
There is a table in a DB, in it there is a tree of objects. When I try to add a record, it says "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);
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();
}
Answer the question
In order to leave comments, you need to log in
The problem was that the DbContext keeps track of this object. And there are two options for solving AsNoTraking () or manually register the creation of a new object
In principle, the for code is strange - i is not used inside the loop.
something apparently in the cycle should be created, but is not created yet.
good.Id = 0 and then good.ParentId = good.Id; ParentId definitely cannot be set to 0, since there can be no such id.
Apparently you need to create a new goodNew inside for and work with it inside the loop, for example goodNew.ParentId = good.Id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question