Reputation: 18812
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?
Upvotes: 4
Views: 3620
Reputation: 19152
Note that the "dirty flag approach" (in its simple form) works for value types (int, bool, ...) and strings but not for reference types. E.g. if a property is of type List<int>
or Address
, you can make it "dirty" without calling the setter method (myCust.Address.City = "..."
calls only the getter method).
If this is the case, you may find useful a 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 like this:
Customer customer = new Customer();
// ... set all properties
if (customer.IsDirty(CustomerController.GetCustomerInformation(id)))
CustomerController.Save(customer);
Upvotes: 1
Reputation: 42526
Take a look at the INotifyPropertyChanged interface. A more detailed explanation of how to implement it is available here.
Upvotes: 3
Reputation: 10008
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.
Upvotes: 3
Reputation: 1077
I am no expert but I would use boolean flag property on the object to indicate it is dirty. I was beat to the answer lol.
Upvotes: 1