![](/img/trans.png)
[英]Updating and managing many-to-many relation in Entity Framework core
[英]Update a many-to-many relation in Entity Framework Core
我正在尝试使用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);
}
编写您的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核心中使用子代更新模型的概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.