Using Data annotations with partial classes and LINQ to SQL

If you’re using LINQ to SQL as your data provider then you will need to add a few extra steps to utilise Data annotations with ASP.NET MVC.

If you have created your own objects then you can append annotations such as [DisplayName(“This is the display name I want in the view”)] directly to the object properties as you can see below. These will then be used by UI Helper and for Model validation by MVC.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MyApp.Models
{
    public class MyObject
    {
        [DisplayName("First Name")]
        public string Property1 { get; set; }

        [DisplayName("Surname")]
        [Required]
        public string Property2 { get; set; }        

    }
}

You can see in the code above that we’ve set some metadata for the DisplayName for the UI Helpers and a Required attribute for model validation.

You can create a partial class to add additional functions and overrides to your LINQ to SQL objects but you cannot add data annotation attributes directly to the LINQ object properties. To achieve this you need to use a separate class and link it to the LINQ to SQL object using the Metadatatype attribute.

Lets assume that the MyObject class is now a LINQ object. We can create a partial class to add additional functions but we cannot use the data annotations shown above (DisplayName and Required)

namespace MyApp.Models
{
    public partial class MyObject
    {
        public string MyAddedFunction()
        {
            return "Some additional data";
        }

    }
}

To add the data annotation attributes we will create another class called MyObject_Validation as shown below

namespace MyApp.Models
{
    public class MyObject_Validation
    {
        [DisplayName("First Name")]
        public string Property1 { get; set; }

        [DisplayName("Surname")]
        [Required]
        public string Property2 { get; set; }        

    }
}

Which overrides the DisplayName on our two fairly poorly named properties Property1 and Property2 to more meaningful names and we assert that Property2 is a required field.

We can now use the Metadatatype  attribute to link the data annotations in MyObject_Validation to MyObject

namespace MyApp.Models
{
    [MetadataType(typeof(MyObject_Validation))]
    public partial class MyObject
    {
        public string MyAddedFunction()
        {
            return "Some additional data";
        }

    }
}

2 thoughts on “Using Data annotations with partial classes and LINQ to SQL

Leave a Reply