Another answer to this question is based almost completely on another question that I found in the Soen.
The author of the question was exploring some ways to update a record and among them he listed some:
Method 1 - Load the original record, change each property and then save.
var original = db.Users.Find(updatedUser.UserId);
if (original != null)
{
original.BusinessEntityId = updatedUser.BusinessEntityId;
original.Email = updatedUser.Email;
original.EmployeeId = updatedUser.EmployeeId;
original.Forename = updatedUser.Forename;
original.Surname = updatedUser.Surname;
original.Telephone = updatedUser.Telephone;
original.Title = updatedUser.Title;
original.Fax = updatedUser.Fax;
original.ASPNetUserId = updatedUser.ASPNetUserId;
db.SaveChanges();
}
The vangatens are to be able to use a Viewmodel, allowing you to have a class without all the properties of the domain class and then facilitate the projection of the View. With this, you need to set the properties you will save, not needing to have all the fields of the domain class in the view and be able to save the change of only the fields you changed.
Already the disadvantages are in:
Have two requests to the database. One to retrieve the original record (record that is in the database with the current data) and the request to persist the data in the database (db.SaveChanges()
).
Method 2 - load the original record and make use of db.Entry(T)CurrentValues.SetValues();
.
var original = db.Users.Find(updatedUser.UserId);
if (original != null)
{
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();
}
Here, the perks are set to modified properties with only two command lines.
Only the changed properties will be sent to the database.
As disadvantages are on account of your view need to have all properties (here, **updateUser**
is not a viewModel, but a class of the )domain itself
Two requests are also made to the database. One to obtain the original record and one to save the record.