LINQ to SQL Validation - Validating Properties and Business Objects - Validation Application Block Can Help

LINQ to SQL Validation - Validating Properties and Business Objects - Validation Application Block Can Help

by David Hayden ( Sarasota Web Design ), Filed: LINQ to SQL

 

LINQ to SQL in Orcas Beta 2 has a number of new features that help with common validation scenarios both at the property level and at the business object level. Much of it is taking advantages of Partial Methods, which is a lightweight alternative to events for code generation.

In LINQ to SQL in Orcas Beta 2 you have the option to validate properties using partial methods that are generated by LINQ to SQL Designer. Hence if I have a Subscriber Class with an Email Property I can generate a separate Subscriber Partial Class that handles the OnEmailChanging Partial Method to validate the Email Property when it is set:

 

public partial class Subscriber {

    partial void OnEmailChanging(string value)
    {
        Regex regex = new Regex("...");
        if (!regex.IsMatch(value))
            throw new ArgumentException("...");
    }
}

 

The nice thing about Partial Methods is that if you don't implement the OnEmailChanging Method as mentioned above, you don't have to deal with the overhead of the call. Unimplemented Partial Methods aren't emitted to IL.

The same example can be done on the business object level. LINQ to SQL in Orcas Beta 2 allows you to define an OnValidate Partial Method if you want to validate the business object before action is taken on it:

 

public partial class Subscriber {

    partial void OnValidate()
    {
        // Validate
        // Throw an Exception if Problems...
    }
}

 

So, LINQ to SQL in Orcas Beta 2 has some nice options for validating the properties and business objects. This isn't anything new or revolutionary, but it is nice that they add some guidance.

Realistically, I don't know how great these options are for larger applications. Partial classes and partial methods are nice for code generation and simple applications, but one is probably better off trying to hook this into Enterprise Library's Validation Application Block and/or using your own separate contract like IValidator<Subscriber> to handle validation.

With something like Enterprise Library's Validation Application Block you also get all broken validation rules returned when doing object validation so you can push this back to the client. And, of course, you can also use the ValidationCallHandler in the Policy Injection Application Block to help separate the validation cross-cutting concerns from your classes.

I am sure Patterns & Practices will come out with some guidance on using LINQ to SQL in the future.

Related Topics:

 

Source: David Hayden ( Sarasota Web Design )

Filed: LINQ to SQL

 

posted on Tuesday, July 24, 2007 1:04 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices