c# - 更新 Entity Framework Core 中的多对多关系

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

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

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

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);
  }

最佳答案

编写您的 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);
}

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

关于c# - 更新 Entity Framework Core 中的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54101665/

相关文章:

c# - Elasticsearch中的每日新索引

asp.net - 如何运行已发布的 Asp.Net core Web 应用程序

c# - 如何在 ASP.NET Core 中覆盖 HandleUnauthorizedRequest

c# - Dotnet Core 默认使用哪个 appsettings.json 文件,环境文件还是父文件?

c# - 控制台.ReadKey();和 Switch 语句 - 使用字母

c# - 如何使用 Newtonsoft.Json 序列化 C# ref 字段?

c# - 拉绳自动换行或显示整个文本

c# - 如何检测 EF Core 何时必须在内存中执行某些 IQueryable 操作

c# - 如何从 EF7 DbContext 获取 ConnectionString

c# - 如何将复杂的 T-SQL 转换为 Linq