Integrating xVal Validation with Linq-to-Sql

In a previous post I showed you how you can use xVal and the IDataErrorInfo class to add validation to your 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.



This entry was posted in .NET and tagged , , , , , . Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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