[英]How to update tables in many-to-many relationship in Entity Framework Core?
我有兩個處於多對多關系中的實體和 3 個表:
例如,我有商店清單:
ShopA, ShopB, ShopC, ShopD
我想添加一個新客戶,為此我選擇了 2 家商店(例如 ShopA 和 ShopC)。
我所做的是:
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();
我從 EF 那里得到錯誤,它不能將實體與相同的主鍵放在一起。 這意味着 EF 嘗試將新Shops
存儲到數據庫中。
我的問題是:如何解決它並只更新連接表?
PS:我看到了另一個帖子,但我找不到可以幫助我的解決方案。
你應該提供更多信息。 順便一提。
這是更新后的代碼:-
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();
希望它能解決您的問題。
我想添加一個新客戶,為此我選擇了 2 家商店(例如 ShopA 和 ShopC)。
我有如下建議:
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();
我的演示代碼如下:
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();
結果:
通常,當我看到此錯誤時,是由於使用了 AsNoTracking 方法。
如果您在獲取商店列表時使用 AsNoTracking 方法,刪除該方法應該可以解決您的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.