【问题标题】:Update a many-to-many relation in Entity Framework Core在 Entity Framework Core 中更新多对多关系
【发布时间】:2019-01-09 14:57:33
【问题描述】:

我正在尝试使用 Entity Framework Core 更新 ASP.NET Core MVC 控制器中的 many-to-many 关系。我设法让它工作以添加到关系中,但没有更新(如果我只是打开/保存实体,则会导致重复键错误)。

如何在有效地更新/插入新关系之前从数据库中删除关系?

public async Task<IActionResult> Edit(int id, [Bind("Id,Name,SalesClerkIds")] Plant plant)
{
        if (id != plant.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                plant.SalesClerks = new List<PlantSalesClerk>();

                if (plant.SalesClerkIds != null)
                {
                    foreach (var scId in plant.SalesClerkIds)
                    {
                        plant.SalesClerks.Add(new PlantSalesClerk()
                        {
                            Plant = plant,
                            User = _context.Users.FirstOrDefault(u => u.Id == scId)
                        });
                    }
                }

                _context.Update(plant);

                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PlantExists(plant.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }

        return View(plant);
  }

【问题讨论】:

    标签: c# asp.net-core entity-framework-core


    【解决方案1】:

    将你的Edit post 方法写如下:

    public async Task<IActionResult> Edit(int id, [Bind("Id,Name,SalesClerkIds")] Plant plant)
    {
        if (id != plant.Id)
        {
            return NotFound();
        }
    
        if (ModelState.IsValid)
        {
            try
            {
                Plant plantToBeUpdated = await _context.Plants.Include(p => p.SalesClerks).FirstOrDefaultAsync(p => p.Id == id);
    
                if (plantToBeUpdated != null)
                {
                     plantToBeUpdated.SalesClerks.Clear(); // Here you have to clear the existing children before adding the new
    
                     if (plant.SalesClerkIds.Count > 0)
                     {
                          foreach (var scId in plant.SalesClerkIds)
                          {
                             plantToBeUpdated.SalesClerks.Add(new PlantSalesClerk()
                             {
                                PlantId = plantToBeUpdated.Id,
                                UserId = scId
                             });
                         }
                     }
    
                     plantToBeUpdated.Name = plant.Name;
    
                    // Map other properties here if any
    
                    _context.Plants.Update(plantToBeUpdated);
    
                    await _context.SaveChangesAsync();
               }
    
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PlantExists(plant.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
    
        return View(plant);
    }
    

    注意:我没有看到您的模型类和编辑视图。我已经根据您的代码假设了一切。因此可能需要进行一些调整,但这是在 EF 核心中更新模型的概念。

    【讨论】:

    • 非常感谢...它的工作方式是这样的!我认为会有一种更“自动化”的方式来做到这一点,但我对这个解决方案也很好。
    • 所以,它只是 - “删除所有内容并将其添加为新的”。 ..?
    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2020-03-12
    相关资源
    最近更新 更多