My Shop and Product entities have a one to many relationship, please see my models
public class Product
{
public int ID { get; set; }
public string Name {
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.