Another answer to this question is almost completely based on another question I found in SOen .
The author of the question was exploring some ways to update a record and among them he listed a few:
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();
}
Vangatens are able to use a ViewModel , so you can have a class without all the properties of the domain class and then facilitate View's projection. With this, you need to set the properties that you are going to save, so you do not need to have all fields of the domain class in the view and you can save the change of only the fields you have changed.
Disadvantages are in:
Have two requests to the database. One to retrieve the original record (the 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 advantages are to set the modified properties with only two command lines. Home
Only the changed properties will be sent to the database.
Disadvantages because your view needs to have all properties (here, **updateUser**
is not a viewModel, but a class of its own)
Two requests are also made to the database. One to get the original record and one to save the record.