Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the best way to implement change tracking on an object

Tags:

c#

.net

I have a class which contains 5 properties.

If any value is assingned to any of these fields, an another value (for example IsDIrty) would change to true.

public class Class1 {     bool IsDIrty {get;set;}      string Prop1 {get;set;}     string Prop2 {get;set;}     string Prop3 {get;set;}     string Prop4 {get;set;}     string Prop5 {get;set;} } 
like image 872
user137348 Avatar asked Mar 02 '10 14:03

user137348


People also ask

What is change tracker?

Change tracking is a lightweight solution that provides an efficient change tracking mechanism for applications. Typically, to enable applications to query for changes to data in a database and access information that is related to the changes, application developers had to implement custom change tracking mechanisms.

What is change tracking in Entity Framework?

The Change Tracking tracks changes while adding new record(s) to the entity collection, modifying or removing existing entities. Then all the changes are kept by the DbContext level. These track changes are lost if they are not saved before the DbContext object is destroyed.

How do I turn on Track Changes?

On the Review tab, select Track Changes. In the Track Changes drop-down list, select one of the following: To track only the changes that you make to the document, select Just Mine. To track changes to the document made by all users, select For Everyone.


1 Answers

To do this you can't really use automatic getter & setters, and you need to set IsDirty in each setter.

I generally have a "setProperty" generic method that takes a ref parameter, the property name and the new value. I call this in the setter, allows a single point where I can set isDirty and raise Change notification events e.g.

protected bool SetProperty<T>(string name, ref T oldValue, T newValue) where T : System.IComparable<T>     {         if (oldValue == null || oldValue.CompareTo(newValue) != 0)         {             oldValue = newValue;             PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(name));             isDirty = true;             return true;         }         return false;     } // For nullable types protected void SetProperty<T>(string name, ref Nullable<T> oldValue, Nullable<T> newValue) where T : struct, System.IComparable<T> {     if (oldValue.HasValue != newValue.HasValue || (newValue.HasValue && oldValue.Value.CompareTo(newValue.Value) != 0))     {         oldValue = newValue;         PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(name));     } } 
like image 107
Binary Worrier Avatar answered Sep 24 '22 06:09

Binary Worrier