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.
The model is updated successfully, the changes also get added to the peopleInvolved
object successfully, however, the SaveChanges()
call doesn't save anything.
.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. Then you change that variable to be a reference to the PeopleInvolved
property on the model object. 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.
db.PeopleInvolved.Attach(model.PeopleInvolved);
db.Entry(model.PeopleInvolved)).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.