How to add data annotation for entities automatically created by Data-First?

Blaise picture Blaise · Jan 19, 2012 · Viewed 7.7k times · Source

If model-first, we use [MetadataType(typeof(ConceptMetadataSource))] to attach a MetadataSource file which contains all the data annotations like [HiddenInput(DisplayValue = false)] or [Display(Name = "Title")].

For example:

[MetadataType(typeof(ConceptMetadataSource))]
public partial class Concept
...

Now, I am using database-first approach since there is an existing database. This time, the entity classes are automatically created by edmx model. At the beginning of each entity class, there is lines of comment below:

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

Since the code will be regenerated once we modify a table in the database, the data annotations will be wiped out each time the entity classes are regenerated.

Can anyone tell me what is the best method to annotate those entity classes? Thank you.

Answer

Rakesh Nandrajog picture Rakesh Nandrajog · Feb 6, 2013

All you have to do is create another partial class and use metadatatype attribute. Here is the sample code

//This is generated by EDMX

namespace DataLayer
{
    using System;
    using System.Collections.Generic;

    public partial class Customer
    {
        public Customer()
        {
            this.CustomerAddresses = new HashSet<CustomerAddress>();
            this.CustomerOrders = new HashSet<CustomerOrder>();
        }

        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailId { get; set; }


        public Nullable<System.DateTime> DateOfBirth { get; set; }

        public virtual ICollection<CustomerAddress> CustomerAddresses { get; set; }
        public virtual ICollection<CustomerOrder> CustomerOrders { get; set; }
    }
}

Add following code manually

namespace DataLayer
{
    [MetadataType(typeof(CustomerMetaData))]
    public partial  class Customer
    {

    }
    public class CustomerMetaData
    {
        [StringLength(10, ErrorMessage = "First name must be 25 characters or less in length.")]
        [Required(ErrorMessage = "First name is required.")]
        public String FirstName { get; set; }
    }
}