Detecting changes in property values โ€‹โ€‹of a .NET object?

I have a form that is used to insert / display and update. In edit (update) mode, when I transfer my BO back to the controller, what is the best way to check if any of the property values โ€‹โ€‹have been changed to update in the data store?

 textbox1.text = CustomerController.GetCustomerInformation(id).Name 

The client object is returned from the controller. I need to check if the object is dirty in order to perform the update. I would suggest that the object sent from the client should be compared to the one sent from the controller when I do this:

 CustomerController.Save(customer) 

How is this usually done?

+4
source share
4 answers

A good way is to have the IsDirty flag on the object and all updatable properties update this flag if they are changed. If the object is loaded, the flag is initialized to false.

The example property will look like this:

 public string Name { get { return _name; } set { _name = value; _isDirty = true; } } 

Then, when you return the object back, you can simply check Customer.IsDirty to see if you need to make changes to the database. And as an added bonus you will get some humor from the received text :) (oh dirty customers)

You can also always save the object, regardless of whether it has been modified, I prefer to use the flag.

+3
source

Take a look at the INotifyPropertyChanged interface. A more detailed explanation of how to implement it is available here .

+3
source

I am not an expert, but I would use the boolean flag property on the object to indicate that it is dirty. I was beaten up to answer lol.

+1
source

Note that the dirty flag approach (in its simple form) works for value types (int, bool, ...) and string, but not for reference types. For instance. if the property is of type List<int> or Address , you can make it dirty without calling the setter method ( myCust.Address.City = "..." only calls the getter method).

If so, you can find a useful reflection-based approach (add the following method to your BO):

 public bool IsDirty(object other) { if (other == null || this.GetType() != other.GetType()) throw new ArgumentException("other"); foreach (PropertyInfo pi in this.GetType().GetProperties()) { if (pi.GetValue(this, null) != pi.GetValue(other, null)) return true; } return false; } 

You can use it as follows:

 Customer customer = new Customer(); // ... set all properties if (customer.IsDirty(CustomerController.GetCustomerInformation(id))) CustomerController.Save(customer); 
+1
source

All Articles