I need to edit my record in database. I don’t think that I’m doing it good enough. I’ve tried make code shorter by dev = newDev; but it is not saving it then.
Code
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(Dev newDev)
{
try
{
if (TryUpdateModel(newDev) == true)
{
var dev = _db.Devs.Where(x => x.ID == newDev.ID).Single();
dev.Title = newDev.Title;
dev.Body = newDev.Body;
dev.Tags = newDev.Tags;
dev.Image1 = newDev.Image1;
dev.Image2 = newDev.Image2;
dev.Image3 = newDev.Image3;
dev.Image4 = newDev.Image4;
_db.SubmitChanges();
return RedirectToAction("");
}
else
{
return Content("Fail.");
}
}
catch
{
return View();
}
}
Can you help me optimize my code here?
If you’re using Entity Framework (it looks like it?) then you can’t update entities this way.
The Entity Framework uses change tracking to understand what changes have happened to an entity. To do this, it keeps a list of the specific instances that are loaded from that context, and what their initial state was, so it can detect what changes have been made to those instances before you call
SaveChangeson the context.When you assign directly to a reference type, you’re just reseating the reference. You aren’t changing the initial object instance. Existing references to that instance (like the one the Entity Framework keeps internally to keep track of changes) don’t change, and you will end up pointing at different object instances.
So, just use your code the way you have it now. This is the only way to blindly update every field. If nothing was updated, the Entity Framework’s change tracking should cause
SaveChangesto do nothing. If something was updated, it will perform the corresponding SQL to persist the changes to the DB.