I have two entities in a many-to-many relationship and 3 tables:
- Customer
- Shop
- CustomerAndShopAssignemnt (join table)
I have list of shops for example:
ShopA, ShopB, ShopC, ShopD
and I want to add a new Customer, for which I choose 2 shops (for example ShopA and ShopC).
What I do is:
var listOfChoosenChops = // get the shops entities from db by ID's
var newCustomer = new Customer()
{
Name = "Martin",
Age = 44,
Shops = listOfChoosenChops
}
_context.Customers.Add(newCustomer)
_context.SaveChanges();
I get error from EF that it can't put the entities with the same primary keys. That means that EF tries to store new Shops
into the database.
My question is: how to solve it and update only join table?
PS: I saw another posts but I'm not able to find solution which will help me there.
CodePudding user response:
You should have provide more information. by the way. the error you are encountering is maybe Entity Framework is trying to insert new Shop entities into the database instead of just updating the join table.
Here is the updated code:-
var existingShops = _context.Shops.Where(s => s.ShopId == shopId).ToList();
var newCustomer = new Customer()
{
Name = "Martin",
Age = 44
};
newCustomer.Shops = existingShops;
_context.Customers.Add(newCustomer);
_context.SaveChanges();
Hope it will resolve your issue.
CodePudding user response:
I want to add a new Customer, for which I choose 2 shops (for example ShopA and ShopC).
I have a suggestion like below:
var ShopA = // get the ShopA from db by ID
var ShopC = // get the ShopC from db by ID
var newCustomer = new Customer()
{
Name = "Martin",
Age = 44,
};
newCustomer.Shops.Add(ShopA);
newCustomer.Shops.Add(ShopC);
_context.Customers.Add(newCustomer)
_context.SaveChanges();
My demo code like:
var s1 = _context.Supplier.FirstOrDefault(x => x.SupplierID == 1);
var s2 = _context.Supplier.FirstOrDefault(x => x.SupplierID == 2);
var newCustomer = new Product()
{
ProductName = "p3",
};
newCustomer.Supplier.Add(s1);
newCustomer.Supplier.Add(s2);
_context.Product.Add(newCustomer);
_context.SaveChanges();
result:
CodePudding user response:
Typically when I see this error, it's due to using the AsNoTracking method.
If you're using the AsNoTracking method when getting your list of shops, removing that method should solve your error.