Main Contents

Integrating xVal Validation with Linq-to-Sql

Schotime @ March 31, 2009

.NET

In a previous post I showed you how you can use xVal and the IDataErrorInfo class to add validation to your Asp.net MVC website. In this post I will extend that to Linq-to-Sql and the classes it generates.

The northwind database has a suppliers table. The info contained below is using that table with linq-to-sql.

After adding the table to the designer, a Supplier class gets constructed in the background. This class is a partial class which means we can add to it without changing the code auto-generated in the designer.cs file.

We can then create a partial class called Supplier inheriting from Custom Validation and add a MetadataType attribute to it. This attribute specifies the class for which use for validating the Supplier class.

    [MetadataType(typeof(SupplierValidation))]
    public partial class Supplier : CustomValidation
    {
    }

We can then create the SupplierValidation class specifying the properties of the Supplier class we would like to be validated. For instance here I only want to validate the ContactName and the ContactTitle of the Supplier.

        public class SupplierValidation
    {
        [Required]
        public string ContactName { get; set; }

        [Required, Range(0, 10)]
        public string ContactTitle { get; set; }
    }

This specifies that both fields are required and that the ContactTitle cannot be more than 10 characters in length.

The other benefit of using the buddy class here is that if you need to regenerate a table in the linq-to-sql designer, you won’t lose your changes because they’re contained in a separate file.

From here when a Supplier gets passed to in as a parameter on a Controller action it will be validated using the rules in the Supplier Validation class.

Cheers,

Adam


book mark Integrating xVal Validation with Linq-to-Sql in del.icio.us submit Integrating xVal Validation with Linq-to-Sql to digg.com


Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Feed
24,360 spam comments
blocked by
Akismet