menu

arrow_back Where is the violation of the foreign key?

by
0 votes
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

2 Answers

by
 
Best answer
0 votes
The problem was that the DbContext was tracking this object. And there are two ways of solving AsNoTraking() or manually prescribing the creation of a new object
by
0 votes
In principle, the for code is strange - i inside the loop is not used.
Something must be created in the loop, but so far it is not.

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 the for loop and work with it inside the loop, e.g. goodNew.ParentId = good.Id

1 comment

ParentId refers to another record