Updating Entity Framework Objects with Changed Data
Assuming you're using the latest version of Entity Framework, the easiest way to update your database is to use DbContext's Entry class: It's just two lines of code no matter how many properties your object has.
As an example, here's some code that accepts an object holding updated Customer data, retrieves the corresponding Customer entity object from the database, and then gets the DbEntityEntry object for that Customer object:
public void UpdateCustomer(Customer custDTO)
CustomerEntities ce = new CustomerEntities();
Customer cust = ce.Customers.Find(custDTO.Id);
if (cust != null)
DbEntityEntry<Customer> ee = ctx.Entry(cust);
Now that you have the Entry object for the object you retrieved from the database, you can update the current values on that retrieved entity object with the data sent from the client:
The CustomerDTO doesn't have to be a Customer class. SetValues will update properties on the retrieved Customer class with properties from the CustomerDTO that have matching names.
It also matters that this code updates the retrieved entity object's current values. Entity Framework also keeps track of the original values when the Customer object was retrieved and uses those to determine what actually needs to be updated. Because the original values are still in place, the DbContext object can tell which properties actually had their values changed by the data from CustomerDTO through SetValue. As a result, when you call the DbContext's SaveChanges method, only those properties whose values were changed will be included in the SQL Update command sent to the database.
Of course, you did have to make a trip to the database to retrieve that Customer entity object. If you'd like to avoid that trip (and, as a result, speed up your application) you can do that, but it does require more code.
Posted by Peter Vogel on 10/04/2018 at 1:51 PM