Tips & Tricks: Extending your Entity Framework classes

There are different reasons why you would like to extend the existing properties on your entity framework classes, for instance when you want to add data validation attributes or the display attribute, commonly used in ASP.Net MVC to set the ‘display’ name of the property.

Here is how to do it without editing your auto generated Entity Framework (.edmx) file. ‘author’ is the entity framework class.

    [MetadataType(typeof(authorMetadata))]
    public partial class author
    {
    }

    public class authorMetadata
    {
        [Display(Name = "First name")]
        public string firstname { get; set; }
    }

We further extend the original author class by adding another partial class and specify which class contains the metadata for the class using the Metadatatype attribute.

2 Comments.

  1. Been searching for this for about an hour so I could use the AllowHtml attribute. I didn’t want to use the ValidateInput(false) on my controller. This resolved my issue. Thank you so much for posting!!

  2. This is great. How can it be done for all the classes created in the EDMX ? I continue to get a Duplicate ‘MetadataType’ attribute error.