Search code examples
c#entity-framework-4asp.net-mvc-4data-annotations

Data Annotations not showing for partial Entity classes in MVC 4


I have seen dozens of explanations of how to add metadata annotations, via partial classes, to classes generated via Entity Framework, database first.

Can someone tell me why these new display values are not showing in my views? Both of these are part of the same namespace as my entity framework generated classes.

[MetadataType(typeof(xRef_CodesMetadata))]
        public partial class xRef_Codes
        {
        }

public class xRef_CodesMetadata
    {
        public int CodeID { get; set; }
        public int CTB_ID { get; set; }

        [Required(ErrorMessage = "Please type a name")]
        [Display(Name = "Code Name")]
        [Column(TypeName = "Code Name")]
        public string CodeName { get; set; }

        [Required(ErrorMessage = "Please type a Description")]
        [Display(Name = "Description")]
        [Column(TypeName = "Description")]
        public string Description { get; set; }     
    }

Fragment of View:

<th>
    @Html.DisplayNameFor(model => model.OfCodeID)
</th>
<th>
    @Html.DisplayNameFor(model => model.CodeName)
</th>
<th>
    @Html.DisplayNameFor(model => model.Description)
</th>   

Solution

  • This has been resolved! I have looked at literally 30 maybe 40 tutorials about why this Entity Framework "Database First" partial classes wasn't working. Then I found this post that gave the following suggestion:

    Sorry this is so late, but I just solved a similar scenario myself. I believe the line

    [MetadataType(typeof(CompanyMD))]

    belongs in the partial class generated by the EF, even though it will be erased if and when you change the model. So your EF-generated file should look like this:

    To see the rest of the post go this link... MVC 4 EF5 Database First set Default Values in Partial Class