Wednesday 7 October 2009

Using OnValidate method in LINQ to SQL

If you are using LINQ to SQL you may have noticed the OnValidate partial method.

public partial class Person : INotifyPropertyChanging,
                  INotifyPropertyChanged
{
     ...
     partial void OnValidate(ChangeAction action);
     ...
}

This method gets automatically called when the class participates in the DataContext SubmitChanges.

When working with LINQ to SQL classes I prefer to keep my code generated classes separated from any modifications or customisations.  Normally, I will create a folder in my project called ExtendedClasses, there I can extend my business objects, giving them a <classname>.extended.cs file name.  This allows me to regenerate my business objects without fear of losing these customisations.

So, in my extended class file I will include...

partial void OnValidate(ChangeAction action)
{
    if (action == ChangeAction.Insert)
    {
        //Do validation for inserts
    }
   
    if (action==ChangeAction.Insert ||
        action==ChangeAction.Update)
    {
        //Do basic validation for inserts and updates
    }
}

I avoid including any business rules in this class level validation, and stick to data related validation, such as field lengths, data ranges and required fields all based on my data model.  Any validation errors get raised by throwing an exception.
Because the OnValidate method is private, you may want to include a public Validate method.

public void Validate()
{
    if (PersonId==Guid.Empty)
    {
        OnValidate(ChangeAction.Insert);
    }
    else
    {
        OnValidate(ChangeAction.Update);
    }
}

With the public Validate method I can validate my business object from the UI layer before passing it down to my services layer.

try
{
    person.Validate();
}
catch (Exception e)
{
    MessageBox.Show(e.Message + "\n\n" + e.StackTrace);
    return;
}

No comments: