Showing posts with label Data Annotation. Show all posts
Showing posts with label Data Annotation. Show all posts

August 20, 2014

Models in an MVC application are just classes and therefore it is easy to add data annotations in the class itself. When MVC generates the views, the different field names and validation messages and datatypes are automatically generated. For example, the following can be a data model in an application.

The above LoginModel is copied from the auto generated template in an MVC application. Note that the data annotations like "Required", "DataType" are applied. However, if the model is generated from Entity Framework, these data annotations will not appear and how would we add the necessary data annotations.

So, to add annotations to an Entity model, we can take advantage of the System.ComponentModel.DataAnnotations.MetadataTypeAttribute class that allows to specify the metadata class to use with the data model class. So, we need to create a new class specify the metadata attribute which will link the data model class to another class which will contain all the data annotations for the necessary fields.

Here is an example of how this would work.

[MetadataType(typeof(AccountMetaData))]
public partial class Account
{
    //empty class just to apply class level attribute
    //imagine this as data annotations for Account
    //is in AccountMetaData class
}

public class AccountMetaData
{
    //same property name & type as in the Entity model
    [Display(Name = "Date of Birth of date")]
    public DateTime DateOfBirth;

    [Required]
    [MinLength(6, ErrorMessage = "Too short")]
    public string AnnountName;
}
Reference: Shahed Kazi at AspNetify.com