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:
[MetadataType(typeof(EmploymentMetadata))] public partial class Employment { internal sealed class EmploymentMetadata { [Required(ErrorMessage="Id is required")] public Int32 Id { get; set; } [Required(ErrorMessage="Company Name is required")] [StringLength(250)] public String CompanyName { get; set; } [Required(ErrorMessage="Supervisor is required")] [StringLength(250)] public String Supervisor { get; set; } [StringLength(100)] [DataType(DataType.EmailAddress)] public String EmailAddress { get; set; } [Required(ErrorMessage="Phone Number is required")] [StringLength(15)] [DataType(DataType.PhoneNumber)] public String PhoneNumber { get; set; } [DataType(DataType.DateTime)] public DateTime DateStart { get; set; } [DataType(DataType.DateTime)] public DateTime DateEnd { get; set; } [Required(ErrorMessage="Reason For Leaving is required")] [StringLength(1000)] public String ReasonForLeaving { get; set; } } }
To use this T4 template in Visual Studio 2010 follow the steps below:
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.