Yorke Rossington Yorke Rossington - 24 days ago 8
C# Question

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.

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");
}
}

Answer

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();