T4 Metadata and Data Annotations Template

This T4 template handles generating metadata classes from an Entity Framework 4 model and decorates properties with data annotation attributes such as [Required] and [StringLength]. The [DataType] attribute is also applied when appropriate. It'll also generate ErrorMessage values based upon property names for required fields. Camel-cased property names will automatically be split up so that the description doesn't have to be modified in many cases. Once the template generates the metadata classes you can then use them in your project and make modifications as needed (keep in mind you'll probably want to remove the template once it generates the initial code since any further executions will overwrite any changes you may make). An example of a class and associated metadata class generated by the template is shown next:


public partial class Employment
    internal sealed class EmploymentMetadata
	[Required(ErrorMessage="Id is required")]
    	public Int32 Id { get; set; }

	[Required(ErrorMessage="Company Name is required")]
    	public String CompanyName { get; set; }

	[Required(ErrorMessage="Supervisor is required")]
    	public String Supervisor { get; set; }

    	public String EmailAddress { get; set; }

	[Required(ErrorMessage="Phone Number is required")]
    	public String PhoneNumber { get; set; }

    	public DateTime DateStart { get; set; }

    	public DateTime DateEnd { get; set; }

	[Required(ErrorMessage="Reason For Leaving is required")]
    	public String ReasonForLeaving { get; set; }



To use this T4 template in Visual Studio 2010 follow the steps below:

  1. Download the sample project from the Downloads area of the project to see the template in action
  2. Add the template .tt file into your Entity Framework project
  3. Change the Source CsdlPath to point to your Entity Framework 4 .edmx file within the T4 template
  4. The name you give the .tt file will be the name given to the code file it generates
  5. Don't make changes directly to the generated code as you customize your data annotations. You'll need to copy it to a file you control. Otherwise the template may overwrite changes you make.

This is one of those "works on my machine" types of projects. I needed to simplify the process of creating metadata buddy classes for an ASP.NET MVC 3 project and decided to bite the bullet and create something custom since I couldn't find anything out there that did this (although I'm guessing there must certainly be T4 template that does this type of thing out there somewhere). If you know of another T4 template that handles this functionality please let me know.

Last edited Feb 20, 2011 at 9:26 PM by dwahlin, version 9