Helper Methods for Validating Generated Linq-to-Entities edmx Files using Partial Classes

Centralized client and server side validation as well as property and method additions to auto-generated classes

Say I have an auto-generated Widget class (from a database, generated into a .edmx file):
namespace My.NameSpace
{
    public partial class Widget
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Now I want to add some methods and validation to the class, but I do not want to edit the class directly. What I need to do is make a partial class and add the things in there. This accomplished two things: 1. separates logic from structure and 2. separates the files so another auto-generation or update will not lose the work you do. This is very simple to do, here is an example:
// be SURE that it is in the same namespace
namespace My.NameSpace
{
    //System.ComponentModel.DataAnnotations
    [MetadataType(typeof(VWidget))]
    public partial class Widget
    {
        // I want to add another property
        public string FullName
        { get { return Name + Id; } }
    }

    // this is the validation segment
    // this is the same as the class name above
    public class VWidget
    {
        [Display(Name = "Widget Name")]
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
    }
}

Now this was very simple, but it shows how to add this in. First of all, there is a new property to Widget called 'FullName' which will combine the 'Name' and 'Id' properties. Not really all that useful, but you can see how it is used.

The next part is really cool, you can put all of your validation in the 'VWidget' class (name doesn't really matter here). Here you can see that 'Name' is now required, has a max length of 50 characters, and a label will display "Widget Name" instead of the default property name. This way, if you are using this library with MVC, you can do something this simple:
@using (Html.BeginForm())
{ 
    @Html.ValidationSummary()
    @Html.LabelFor(x => x.Name)
    @Html.EditorFor(x => x.Name)
}

And you will be pushing client-side validation as well as a centralized area to hold your custom labels. On top of that, in your code, if you simply include:
if (ModelState.IsValid)

You will be enforcing server-side validation as well.

Later I will get into how you can use .resx files for localization and centralization along with these partial classes.

Pingbacks and trackbacks (1)+

Add comment

Loading