Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting changes in property values of a .NET object?

I have a form which is used to insert/display and update. In the edit mode (update), when I pass my BO back to the Controller, what is the best possible way to check if any of the property values were changed, in order to execute the update to the datastore?

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

A customer object is returned from the controller. I need to check if the the object is dirty in order to execute an update. I would assume the object sent from the client has to be compared with the one sent from the controller when I do:

CustomerController.Save(customer)

How is this normally done?

like image 988
Saif Khan Avatar asked Mar 02 '23 05:03

Saif Khan


1 Answers

A good way is to have an IsDirty flag on the object and have all the setable properties update that flag if they are changed. Have the flag initialized to false when the object is loaded.

An example property would look like this:

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

Then when you get the object back you can simply check, Customer.IsDirty to see if you need to commit the changes to the database. And as an added bonus you get some humour from the resulting text :) (oh those dirty customers)

You can also opt to always save the object regardless of whether it has been changed, my preference is to use a flag.

like image 69
vfilby Avatar answered Mar 06 '23 06:03

vfilby