当提交表单并通过我的模型(表单)时,我试图将更改保存到我的DB。
窗体模型有一个PeopleInvolved
对象作为属性。
模型更新成功,更改也成功地添加到peopleInvolved
对象中,然而,SaveChanges()
调用没有保存任何内容。
。. NET Framework 4.5.1 - EF 6.1.1
public class Forms
{
public int Id { get; set; }
public string UserId { get; set; }
public PeopleInvolved PeopleInvolved { get; set; }
}
public async Task<ActionResult> EditForm(Forms model, string returnUrl)
{
ViewData["ReturnUrl"] = returnUrl;
ApplicationUser user = await GetCurrentUserAsync();
if (!ModelState.IsValid)
return RedirectToAction("Index", model);
if (model.PeopleInvolved != null)
{
PeopleInvolved peopleInvolved = _db.PeopleInvolved.Single(x => x.FormId == user.FormId);
peopleInvolved = model.PeopleInvolved;
_db.SaveChanges();
return RedirectToLocal(returnUrl + "?PeopleInvolved?Success");
}
}
您实际上没有更改数据库中的任何内容。
对数据库的调用返回了一个PeopleInvolved
对象,并在peopleInvolved
变量中存储了对它的引用。然后将该变量更改为对模型对象上的PeopleInvolved
属性的引用。实际上,您永远不会更改从数据库调用返回的对象。
简单的解决方案是这样做
peopleInvolved.Property1 = model.PeopleInvolved.Property1;
peopleInvolved.Property2 = model.PeopleInvolved.Property2;
更新从数据库返回的实际对象
您可以这样更新。如果你必须重写model.PeopleInvolved.FormId。
db.PeopleInvolved.Attach(model.PeopleInvolved);
db.Entry(model.PeopleInvolved)).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();