Search code examples
c#asp.netcustom-attributeschange-tracking

C# and ASP.NET custom property attributes and determining if properties changed


I am working on a project where we want to keep a history of a particular object. On save I want a method on the object that will determine if it has changed so that I can call a method to save its current state to history. E.g. I populate a form from an object the user makes changes (or possibly not) and submits the from. I want to take my original object and a copy of that object that has been updated from the form and determine if it has changed at all. Additionally I may decide at some point that certain properties don't matter (e.g. if Name changes I won't track it).

I'm thinking the easiest/most flexible way to accomplish this would be if I could give the properties I care about a custom attribute [ChangeTracked] and then I could use reflection to get a list of all properties with that attribute and loop through them comparing A.property == B.property to determine if any have changed.

Would this work? Is there a significantly better/easier way to handle this, like some sort of built in method you can add to an object to determine if the values of any properties have changed? Whatever the solution some psudo code would be appreciated. Just as a point of clarification the solution needs to determine if the value I care about has actually changed not just if it has been assigned since it was created i.e. if I set Name="bob" and it was already "bob" before my assignment this does not count as a change.


Solution

  • It ain't fancy, but this is the tried and true brute force method. Just add a private property to the object named IsDirty. For properties that you want to track, just add IsDirty=True to the property Set routine. For more complicated "do I care" rules, just code them into the property set.

    The page button's click event can fire a Save event that writes all the values from the textboxes and dropdowns into the object properties, then calls the object Save method, which tests the IsDirty property before doing anything.