+3  A: 

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.

vfilby
Put the IsDirty property on a BaseObject that Customer will inherit from.
Kon
The properties on the Customer object have to know to update the flag though.
vfilby
oh, true. I was thinking differently.. that if one property is dirty, might as well update all of them. Since you'll be doing an UPDATE on the Customer table.
Kon
@vfilby: That doesn't change the usefulness of having IsDirty on the base class of all your business objects.
Harper Shelby
if i set properties in the DAL and pass the object to the Controller, who then pass it to the form, at the form level it's already dirty..no? Since i've already set properties in the DAL. I would then need to reset dirty to false at controller level.
Saif Khan
@Saif: Your DAL can load all the properties and set the IsDirty flag to false.
vfilby
@Harper Shelby: Yep, just noting that you still have to update the flag in the child classes.
vfilby
+1  A: 

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.

OutOFTouch
Welcome aboard, OutOfTouch. Sometimes you gotta type really fast here, LOL.
DOK
Aye, welcome... and nah na nah na nah nah. :)
vfilby
+3  A: 

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

Scott Dorman
+1  A: 

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);
Panos