Search code examples
model-view-controlleref-database-first

How to preserve dataannotation in MVC data first approach


I am using MVC database first approach and created one .edmx file.

Now my all the tables are available in this model.tt file. I have also defined some dataannotation on those fields of table.

But What I have noticed that when ever I tried to update this model then value of dataanotation will be lapse.

Any thoughts please.


Solution

  • Yes it's kinda funny how much you read about annotations but you can't actually use them because they get overwritten.

    This is what I found to help me

    http://www.ozkary.com/2015/01/add-data-annotations-to-entity.html

    also this

    https://learn.microsoft.com/en-us/previous-versions/aspnet/ee256141(v=vs.98)

    I don't pretend to understand it but here's a join the dots guide.

    An example generated EF class looks like this:

    public partial class Employee
    {
        public int Emp_ID { get; set; }
        public string Emp_Name { get; set; }
        public Nullable<System.DateTime> Commencement_Date { get; set; }
    }
    

    Definitely do not edit this.

    Instead you create a seperate class file (I called mine metadata.cs and put it in the Models folder) with this in it:

    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel;
    
    namespace MyProject.Models
    {
        [MetadataType(typeof(EmployeeMD))]  // new name for your metadata class
        public partial class Employee    // same name as your EF generated class
        {
        // Nothing in here
        }
    
        internal sealed class EmployeeMD // your metadata class
        {
        [Required]
        [StringLength(50, MinimumLength = 2, ErrorMessage = "Name required")]
        public string Emp_Name { get; set; }
    
    
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> Commencement_Date { get; set; }
        }
    }