简体   繁体   中英

Saving only fields that have changed in Entity Framework 4

I have a Windows Form with some textboxes and a Save button. When the form loads the textboxes are populated with data from an entity in my model. When the user clicks on the save button the values in each textbox are written back to the entity and then SaveChanges is called to commit the data to the database.

What I'd like to know is what is the best way to check if the form contains changes? If it doesn't contain changes then I needn't call SaveChanges and I can save writing the record back to the database. If it does contain changes and the user hasn't clicked on the Save button I want to get the user's confirmation that the changes don't need to be saved.

I thought maybe I could just update the entity's fields and then check its State property before calling SaveChanges but this fails as updating any field, even with an identical value, causes the entity to be marked as modified.

So, my question is, what is the best way to check that changes have actually been made to the form before calling SaveChanges?

Thanks,

Matt

You can check the entity state. Just save the data from the textboxes to the entity ans see if the EntityState is EntityState.Unchanged .

Details here: http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx

Actually updating the field even with the same value as the previous one counts as a modified entity and in most cases this is the correct business rule.

What you could do is keep a copy of the original object that was used to fill the form fields and compare it with the current one using an equality comparer. It's not pretty but it gets the job done in particular cases where you cannot count on the object state manager's opinion of modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM