【发布时间】:2018-01-11 11:48:07
【问题描述】:
我的页面 a 显示了标题记录以及详细记录列表。当用户单击“保存”时,我正在努力寻找一种干净有效的方式来插入/删除/更新详细记录。
详细记录显示在一个 jQuery DataTable 中,每个详细记录背后的视图模型都有一个 IsNew 和 IsRemoved 属性。当用户添加详细记录时,其 IsNew 属性设置为 true。当用户删除一个详细记录时,它会被软删除,并且其 IsRemoved 属性设置为 true。
当用户点击保存并将页面发布到我的控制器时,我的逻辑现在看起来像这样
[HttpPost]
public ActionResult EditData(ViewModel viewModel)
{
// Update the record's header details here
// ...
foreach (var childViewModel in viewModel.Children)
{
// Use AutoMapper to map the view model to a model
MyChildRecord childModel = this.mapper.Map<MyChildRecord>(childViewModel);
if (childViewModel.IsNew)
{
this.context.MyChildRecords.Add(childModel);
}
else if (childViewModel.IsRemoved)
{
this.context.MyChildRecords.Attach(childModel);
this.context.MyChildRecords.Remove(childModel);
}
else
{
this.context.Entry(childModel).State = EntityState.Modified;
}
}
this.context.SaveChanges();
return RedirectToAction("EditData", new { id = viewModel.Id } );
}
我不喜欢这段代码的一点是,即使子记录没有任何改变,我仍然会在数据库中更新它。我能想出的唯一解决方案是
让每个视图模型存储其原始值的副本,然后在用户保存页面时将其当前值与其原始值进行比较。我不喜欢这个解决方案,因为我必须有一堆代码来存储原始值,然后我必须将原始值作为隐藏字段放在我的 ASP 页面上,以便它们在 Web 请求之间传递。
当用户保存页面时,让控制器遍历每个子视图模型,从数据库中加载原始数据,并比较视图模型的当前值以查看该行是否需要更新。我不喜欢这种方法,因为它涉及到很多额外的字段比较代码,而且我仍然需要对数据库进行不必要的访问。
这似乎是一种常见的情况,因此必须有一种普遍接受的方式来执行此操作。我该怎么办?
【问题讨论】:
标签: c# asp.net asp.net-mvc entity-framework ef-code-first