因为要发布到WebApi控制器的模型是与任何实体框架(EF)上下文分离的,所以唯一的选择是从数据库中加载对象图(包括其子项的父项),并比较已添加,删除或添加了哪些子项。更新。(除非您认为在分离状态下(在浏览器中或任何位置)使用自己的跟踪机制来跟踪更改,我认为这比以下情况更为复杂。)它看起来像这样:
public void Update(UpdateParentModel model){ var existingParent = _dbContext.Parents .Where(p => p.Id == model.Id) .Include(p => p.Children) .SingleOrDefault(); if (existingParent != null) { // Update parent _dbContext.Entry(existingParent).CurrentValues.SetValues(model); // Delete children foreach (var existingChild in existingParent.Children.ToList()) { if (!model.Children.Any(c => c.Id == existingChild.Id)) _dbContext.Children.Remove(existingChild); } // Update and Insert children foreach (var childModel in model.Children) { var existingChild = existingParent.Children .Where(c => c.Id == childModel.Id) .SingleOrDefault(); if (existingChild != null) // Update child _dbContext.Entry(existingChild).CurrentValues.SetValues(childModel); else { // Insert child var newChild = new Child { Data = childModel.Data, //... }; existingParent.Children.Add(newChild); } } _dbContext.SaveChanges(); }}...CurrentValues.SetValues可以接受任何对象,并根据属性名称将属性值映射到附加的实体。如果模型中的属性名称与实体中的名称不同,则不能使用此方法,必须逐个分配值。



