Jamey McElveen
Jamey McElveen

Reputation: 18305

How can write to a change log when Entity Frameworks SaveChanges() is called?

I am using Entity Frameworks Code First. I have one entity that I need to keep a change history on. This entity has a double property and when it changes I need to record the amount change amount and date that it occurred. This means I need the old value the new value subtract and post ever time that value changes or when dbContect.SaveChanges() it called.

This project is really simple and I would like to keep it this way so I would prefer not add a service layer. I am simply making repository request in MVC controllers. (I know this is not pure but it is very agile)

How can I intercept changes to this entity so I can write to a change log?

Upvotes: 2

Views: 812

Answers (1)

Jeff Ogata
Jeff Ogata

Reputation: 57803

You can listen for the ObjectContext.SavingChanges event, and then use the ObjectContext.ObjectStateManager property to look for the ObjectStateEntry(s) for the entity type that you are interested in.

ObjectStateEntry has properties to access the CurrentValues and OriginalValues, or only the original values for updatable properties using the GetUpdatableOriginalValues method.

Note: I have not tested this, but hopefully it will work for you.

Upvotes: 3

Related Questions