Easy Dirty Checking with LINQ to SQL

dirtyDog

What is dirty checking?

Dirty checking is simply a way to check an object to see if it contains changes. This can be used to prevent unnecessary database updates. Properly implemented it should also account for the object changing back to its original state.

For example:

We change the spelling of a dog’s name “Spottie” to “Spotty". If we were to test the object it should return dirty.

Then if we decide the original spelling was correct and change it back to “Spottie” the object should no longer return dirty.

How we implemented it:

We wanted to extend our LINQtoSQL generated classes to implement dirty checking. All we had to do was extend the OnLoaded() method to call our copy constructor so that we had a private copy of the original object. Then we can simply check that private object against the current object state property by property to determine if the object was dirty.

partial class Dog
{
    private Dog _Original; 

    // Copy constructor.
    public Dog(Dog previous)
    {
        Name = previous.Name;
        Breed = previous.Breed;
        Age = previous.Age;
        Sex = previous.Sex;
        Weight = previous.Weight;
        Color = previous.Color; 
    } 

    //Here we copy the original object inside of itself for dirty checking
    partial void OnLoaded()
    {
        _Original = new Dog(this);
    } 

    //dirty checking using _Original from copy constructor
    public bool IsDirty
    {
        get
        {
            return
            !(
                this.Name == _Original.Name &&
                this.Breed == _Original.Breed &&
                this.Age == _Original.Age &&
                this.Sex == _Original.Sex &&
                this.Weight == _Original.Weight &&
                this.Color == _Original.Color 
            );
        }
    } 

}

-ctrlShiftBryan

Advertisements

1 Response to “Easy Dirty Checking with LINQ to SQL”


  1. 1 Tomek Perlak September 22, 2009 at 3:36 pm

    Could using a hashcode be an alternative that would save us some memory?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: