Data Annotation on auto generated model classes in Entity Framework

We can have data annotation on model classes so that validation rule will automatically applied to user input. We can have different type of data validations like, Max length, Regex Expression, Required, Numeric, Range etc.
But here we face problem with auto generated model using entity framework. Adding the validation attributes directly to the model class works when you do not expect the database to change; however, if your database changes/updates and need to regenerate the model class, we will lose all of the attributes applied to the model class and we will end up losing important validation rules.
To avoid this problem, we can add a metadata class that contains the attributes. In this approach, the model class can be regenerated without losing all of the attributes that have been applied to the metadata class.

It can be done as follows,
1. Create a class file in model folder (make sure it has same name space as auto generate model classes)
2. Create partial class same as class you want to have data annotation
3. Add MetadataType attribute with type of your class with data annotation to it
4. Create Class with data annotation on properties as required.
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

//make sure the namespace is equal to the other model classes
namespace MvcApplication.Models
{
    [MetadataType(typeof(MyAutogenrateClassMetaData))]
    public partial class MyAutogenrateClass
    {
    }

    public class MyAutogenrateClassMetaData
    {
        [Required]
        public int Id { getset; }

        [StringLength(50)]
        [Display(Name = "First Name")]
        public string FirstName;

        [Range(0, 4)]
        public Nullable<decimal> Grade;
        //...
    }
}


Comments