Entity Framework Update checks to see if a record has changed

I am updating a database table using EF.

This is a simple script in connected mode.

I get the row I want to update

var order = from o in Orders where o.ID = 1 select o; 

Then I update the record as:

 order.FirstName = "First"; order.LastName = "Last"; context.SaveChanges(); 

It works great. EF checks to see if the field has changed and only the field has been updated if this is a new value. I enabled CDC on my SQL server to verify that EF does not overwrite to the database if the value has not changed.

Now I want to put this check in my code for additional logic, that is, I want EF to tell me when the record was updated and when it was not (because the value has not changed). Can anyone tell if there is a way?

I do not want to manually check each field, since I have many fields for comparison.

thanks

+4
source share
1 answer

If anyone is interested, here is what I did. I created the following method to check if any field has changed before saving the changes.

 private Dictionary<Type, bool> IsEntityModified() { Dictionary<Type, bool> entity = new Dictionary<Type, bool>(); var items = _bentities.ObjectStateManager.GetObjectStateEntries(EntityState.Modified); foreach (ObjectStateEntry entry in items) { foreach (string propName in entry.GetModifiedProperties()) { string oldsetterValue, newsetterValue = null; //Get orginal value oldsetterValue = entry.OriginalValues[propName].ToString(); //Get new value newsetterValue = entry.CurrentValues[propName].ToString(); if (oldsetterValue != newsetterValue) { entity.Add(entry.Entity.GetType(), true); } } } return entity; } 
+7
source

All Articles