Using System.ComponentModel.DataAnnotations with Entity Framework 4.0

I haven’t done this for ASP.NET MVC (only for Silverlight) but I believe the same principles would apply. You can create a “metadata buddy class” as below, because the types generated by EF should be partial, thus you can add a bit more to them (like the MetadataTypeAttribute) and then you create this sibling class that holds the metadata.

It’s kind of ugly, but should work. It goes something like this (assuming the EF entity is named “Person”):

[MetadataType(typeof(PersonMetadata))]
public partial class Person { 
  // Note this class has nothing in it.  It's just here to add the class-level attribute.
}

public class PersonMetadata {
  // Name the field the same as EF named the property - "FirstName" for example.
  // Also, the type needs to match.  Basically just redeclare it.
  // Note that this is a field.  I think it can be a property too, but fields definitely should work.

   [Required]
   [Display(Name = "First Name")]
  public string FirstName;
}

Leave a Comment