I have a base class for BLL that includes the following function:
public bool IsDirty { get; protected set; } internal void SetField<TParam>(ref TParam field, TParam value) { if (EqualityComparer<TParam>.Default.Equals(field, value) == false) { field = value; IsDirty = true; } }
In classes that inherit the base class, I use this as a wrapper around a SET object, for example:
public string UserName { get { return _userName; } set { SetField(ref _userName, value); } }
I use the IsDirty property to check if I need to update. If at least one of the properties changes, then save it in the database. This works for most types, but collections and lists can change without using set. I wrote a wrapper for the collection to have the IsDirty flag in the List, which could be tested for change:
public class CollectionChangeTracked<T> : Collection<T> { public bool IsDirty {get; set;} public CollectionChangeTracked() { IsDirty = false; } protected override void InsertItem(int index, T newItem) { base.InsertItem(index, newItem); IsDirty = true; } protected override void SetItem(int index, T newItem) { base.SetItem(index, newItem); IsDirty = true; } protected override void RemoveItem(int index) { base.RemoveItem(index); IsDirty = true; } protected override void ClearItems() { base.ClearItems(); IsDirty = true; } } }
The problem is that now I need to check the Classe IsDirty property and the CollectionChangeTracked.IsDirty flags for updates. I could create a method that runs the test in one place, for example:
public CollectionChangeTracked<ApplicationRole> RolesList { get { return _rolesList; } set { SetField(ref _rolesList, value); } } public override bool IsDirty { get { return ResolveIsDirty(); } protected set { _isDirty = value; } private bool ResolveIsDirty() { bool returnValue; if (_isDirty || RolesList.IsDirty) returnValue = true; else returnValue = false; return returnValue; }
But it looks like I can come up with a cleaner solution that will allow the class containing the collection to subscribe to the IsDirty change of the CollectionChangeTracked object and update IsDirty based on this change. Is this the best approach and how will I implement it?