How to change [DisplayName] of EF generated class properties?

James123 picture James123 · Mar 25, 2013 · Viewed 15k times · Source

We know EF generates classes based on Tables we added to .edmx file. Which will not any [DisplayName] DataAnnotations for them.

How can I add this [DisplayName] of generated classes without modifying them? because generated classes can be overridden If I modify .edmx file (re add the modified table) if database changes. So I don't want modify generate class itself.

EF Generated Class

 public partial class Committee
    {
        public string Committee_Description { get; set; }
        public byte[] Committee_Id { get; set; }
        public string Rn_Descriptor { get; set; }
        public Nullable<System.DateTime> Rn_Create_Date { get; set; }
       ......
       .....

View

 <tr>
            <th>
                @Html.DisplayNameFor(model => model.Item2.GetEnumerator().Current.Committee_Name)
            </th>

Answer

Moho picture Moho · Mar 25, 2013

Use a metadata class and attach it to your entity class via the MetadataTypeAttribute. You specify your data annotation attributes on the properties in the metadata class (no implementation for said properties).

MSDN: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute.aspx

Edit: an initial gotcha is the namespace of the partial class you define to attach the MetadataTypeAttribute. Be sure to change its namespace to the namespace used by the original entity so that it is defining the same class.