ef core one to many relationship throw exception Cannot add or update a child row

房东的猫 提交于 2019-12-02 07:24:57

Declare ShopID as nullable in the Product table, you are doing product.Shop = null;, so it tries to insert ShopID value null in this column. Since you column ShopID in Product table is not nullable, that is why its giving error. Because there is no Id in Shop table which is nullable. So its giving foreign key constraint fails exception. So all you have to do is to make use the nullable foreign key like public int? ShopID.

You shouldn't make ShopID nullable if it's required by design.

The problem you are experiencing is because Add method also recursively marks all entity instances reachable through navigation properties and not currently tracked by the context as Added (i.e. new).

It can be solved in many ways:

  • Setting entity entry to Added instead of Add method:

    _context.Entry(Product).State = EntityState.Added;
    await _context.SaveChangesAsync();
    
  • Setting the navigation property to null before calling Add:

    Product.Shop = null;
    _context.Products.Add(Product);
    await _context.SaveChangesAsync();
    
  • Attaching the navigation property object before calling Add:

    if (Product.Shop != null) _context.Attach(Product.Shop);
    _context.Products.Add(Product);
    await _context.SaveChangesAsync();
    
  • Using Update instead of Add:

    _context.Products.Update(Product);
    await _context.SaveChangesAsync();
    

The last technique is explained in Saving Data - Disconnected Entities - Mix of new and existing entities:

With auto-generated keys, Update can again be used for both inserts and updates, even if the graph contains a mix of entities that require inserting and those that require updating

Since it works only when all entities use auto-generated PKs, and also produces unnecessary updates of the related entities, I don't recommend it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!