Reputation: 15457
It looks like this snippet of code doesn't work unless I include the first line of the snippet which is not referenced anywhere afterwards? Is this how ApplyCurrentValues
method works?
_entities.Contacts.FirstOrDefault(c => c.Id == contactToEdit.Id);
_entities.Contacts.ApplyCurrentValues(contactToEdit);
_entities.SaveChanges();
return RedirectToAction("Index");
This code edits a contact record and saves to the database.
Here's the entire method:
[HttpPost]
public ActionResult Edit(Contact contactToEdit)
{
if (!ModelState.IsValid)
{
return View();
}
try
{
_entities.Contacts.FirstOrDefault(c => c.Id == contactToEdit.Id);
_entities.Contacts.ApplyCurrentValues(contactToEdit);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Upvotes: 0
Views: 204
Reputation: 268255
From my understanding, the object context needs to know somehow which fields have changed.
The fields will appear updated to it only if the context kept record of the original values.
The first line seems to have a side-effect of making the object context aware of the original values (through loading the entity).
Take a look at these two answers.
Upvotes: 2