简体   繁体   English

如何在 Entity Framework Core 中更新多对多关系中的表?

[英]How to update tables in many-to-many relationship in Entity Framework Core?

I have two entities in a many-to-many relationship and 3 tables:我有两个处于多对多关系中的实体和 3 个表:

  • Customer顾客
  • Shop店铺
  • CustomerAndShopAssignemnt (join table) CustomerAndShopAssignemnt(连接表)

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).我想添加一个新客户,为此我选择了 2 家商店(例如 ShopA 和 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.我从 EF 那里得到错误,它不能将实体与相同的主键放在一起。 That means that EF tries to store new Shops into the database.这意味着 EF 尝试将新Shops存储到数据库中。

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. PS:我看到了另一个帖子,但我找不到可以帮助我的解决方案。

You should have provide more information.你应该提供更多信息。 by the way.顺便一提。

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.希望它能解决您的问题。

I want to add a new Customer, for which I choose 2 shops (for example ShopA and ShopC).我想添加一个新客户,为此我选择了 2 家商店(例如 ShopA 和 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:结果:

在此处输入图像描述

Typically when I see this error, it's due to using the AsNoTracking method.通常,当我看到此错误时,是由于使用了 AsNoTracking 方法。

If you're using the AsNoTracking method when getting your list of shops, removing that method should solve your error.如果您在获取商店列表时使用 AsNoTracking 方法,删除该方法应该可以解决您的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM