Why do I need to get an old entity before calling ApplyCurrentValues on another object?
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开发者_StackOverflow社区 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();
}
}
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.
精彩评论