我正在尝试更新ProjectModel中的ProjectEmployees集合。
我想删除所有旧值并设置新值。
我的模特:
public class Project
{
...
public ICollection<ProjectEmployee> ProjectEmployees { get; set; }
}
public class ProjectEmployee
{
public int ProjectId { get; set; }
public virtual Project Project { get; set; }
public int UserId { get; set; }
public virtual Employee Employee { get; set; }
}
public class Employee
{
public int UserId { get; set; }
public User User { get; set; }
...
}
public class ProjectGroupModel //ViewModel
{
public int ProjectId { get; set; }
public ICollection<Employee> ProjectEmployees { get; set; }
}
这是典型的多对多关系。
我的 Controller Action :
[HttpPost("group")]
public async Task<IActionResult> CreateGroup([FromBody] ProjectGroupModel pro)
{
var dbProject = await _context.Project
.Include(p=>p.ProjectEmployees)
.FirstAsync(p => p.ProjectId == pro.ProjectId);
dbProject.ProjectEmployees.Clear();
foreach (var emp in pro.ProjectEmployees)
{
dbProject.ProjectEmployees.Add(new ProjectEmployee()
{
UserId = emp.UserId
});
}
await _context.SaveChangesAsync();
return Ok();
}
当pro.ProjectEmployees为空时,dbProject.ProjectEmployees中的所有记录均已正确删除,并且如果dbProject.ProjectEmployees为空,则添加了来自模型的新记录,但是当dbProject.ProjectEmployees不为空时,我无法设置新记录:
错误:
我试图以数百种方式修复此操作,但始终……是错误的。
最佳答案
它远非完美,但我唯一能使它起作用的方法是从相应的DbSet
中删除项目,并在添加新项目之前调用SaveChanges
:
var dbProject = await _context.Project
.Include(p=>p.ProjectEmployees)
.FirstAsync(p => p.ProjectId == pro.ProjectId);
if (dbProject.ProjectEmployees.Any())
{
_context.ProjectEmployee.RemoveRange(dbProject.ProjectEmployees);
await _context.SaveChangesAsync();
}
foreach (var emp in pro.ProjectEmployees)
{
dbProject.ProjectEmployees.Add(new ProjectEmployee()
{
UserId = emp.UserId
});
}
await _context.SaveChangesAsync();
关于c# - Entity Framework 核心-更新相关集合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39836260/