[英]Entity Framework - saving db changes not working
When submitting a form and passing in my model (Forms) I am trying to save the changes to my DB. 提交表单并传递模型(表单)时,我试图将更改保存到数据库中。
Forms model has a PeopleInvolved
object as a property. 表单模型具有一个
PeopleInvolved
对象作为属性。
The model is updated successfully, the changes also get added to the peopleInvolved
object successfully, however, the SaveChanges()
call doesn't save anything. 该模型已成功更新,更改也已成功添加到
peopleInvolved
对象,但是, SaveChanges()
调用不会保存任何内容。
.NET Framework 4.5.1 - EF 6.1.1 .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");
}
}
You didn't actually change anything from the database. 您实际上并没有更改数据库中的任何内容。
Your call to the database returned a PeopleInvolved
object and stored a reference to it in the peopleInvolved
variable. 您对数据库的调用返回了
PeopleInvolved
对象,并将对它的引用存储在peopleInvolved
变量中。 Then you change that variable to be a reference to the PeopleInvolved
property on the model object. 然后,您将该变量更改为对模型对象上
PeopleInvolved
属性的引用。 You never actually change the object returned from the database call. 您实际上从未更改过从数据库调用返回的对象。
Simplistic solution is to do something like 简单的解决方案是做类似的事情
peopleInvolved.Property1 = model.PeopleInvolved.Property1;
peopleInvolved.Property2 = model.PeopleInvolved.Property2;
to update the actual object that was returned from the database. 更新从数据库返回的实际对象。
You can update like this. 您可以像这样更新。 If you have to override model.PeopleInvolved.FormId with user.FormId update that property.
如果必须使用user.FormId覆盖model.PeopleInvolved.FormId,请更新该属性。
db.PeopleInvolved.Attach(model.PeopleInvolved);
db.Entry(model.PeopleInvolved)).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.