1

In a previous post (ASP.NET MVC 5 Model-Binding Edit View), the answer suggested this Controller code to process an edit-view postback:

public ActionResult Edit(WarrantyModelEditViewModel vm)
{
   if (ModelState.IsValid)
   {
      var warranty = db.Warranties.Find(vm.Id);
     .
     .
     .
}

Question: Is re-querying the database for the warranty in question really the only way to do this in MVC and is it considered a best-practice approach? (I saw this post, How to re-use model data on post back with MVC, but it was a bit dated so I want to be sure my information is current as of MVC 5 and EF 6.)

In addition, I imagine there are various database concurrency issues, such as if the record was modified or deleted by another user after the view is rendered but before postback. Are there any good resources that discuss ways of handling the various scenarios?

Community
  • 1
  • 1
Jazimov
  • 12,626
  • 9
  • 52
  • 59

1 Answers1

2

You can also do an attach the entity which requires only one call to database. Check this solved thread.

In short something like this -

db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
db.SaveChanges();

For your second question to get optimistic concurrency, you can have a column called timestamp and can check for it during updates. Check this tutorial - Handling Concurrency with the Entity Framework in an ASP.NET MVC Application

Community
  • 1
  • 1
ramiramilu
  • 17,044
  • 6
  • 49
  • 66