我有一个或多或少的标准模型:
public class Project { public int ID { get; set; } //... some more properties public DateTime StartDate { get; set; } public int Duration { get; set; } }
如果用户修改了StartDate或项目持续时间,我必须调用一个函数来更新模拟.为了实现这一点,我想检测控制器中字段StartDate和Duration的状态变化.
像这样的东西:
if(project.StartDate.stateChange() || project.Duration.stateChange())
以下是Controller Method的示例:
[HttpPost] public ActionResult Edit(Project project) { if (ModelState.IsValid) { if(project.StartDate.stateChange() || project.Duration.stateChange()) doSomething(); db.Entry(project).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(project); }
任何想法,我怎样才能做到这一点?
解决方法
我相信你可以将编辑过的实体与从数据库中读取的原始实体进行比较.
就像是:
public ActionResult Edit(Project project) { if (ModelState.IsValid) { var original = db.Find(project.ID); bool changed = original.StartDate != project.StartDate || original.Duration != project.Duration; if (changed) { original.StartDate = project.StartDate; original.Duration = project.Duration; doSomething(); db.Entry(original).CurrentValues.SetValues(project); db.SaveChanges(); } } return View(project); }