R
R
Roman2021-04-08 16:09:16
PostgreSQL
Roman, 2021-04-08 16:09:16

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


First, I create the main object, save 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();
        }

PS I checked the data manually, the error is in ParentId

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2021-04-09
@prorom-exe

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

S
Sumor, 2021-04-08
@Sumor

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 question

Ask a Question

731 491 924 answers to any question