Wednesday 10 April 2013

Model validation in entity framework through Data Annotation

Here is the sample code to implement model validation through data annotation using entity framework.

Steps to follow:
  1. Create a file to store your information say MyDataAnnotations.
  2. Now create a metadata class(preferably put the class name as ClassNameMetaData for naming convention like if your class name is Account then it can be AccountMetaData. It will help you finding your metadata class in future). Assign validations to your model properties and it will reflect when using that model class in your UI.
  3.  Third and last step would be to assign your model class with MetaDataType attribute. For this simple put your attribute to the class like this [MetadataType(typeof(AccountMetaData))] and you are done.
Here in this example I have  taken my class name as SampleClass and metadta name as SampleClassMetaData. I have created a regular expression validation to the property Email which exists in my SampleClass. Next I assigned the MetaDataType attribute to my SampleClass and that's all. You can create your own custom validation attributes also and can use here. That I will explain in my upcoming posts. Use the code in your app and enjoy.

Sample Code:


 public partial class SampleClassMetaData
    {
        [RegularExpression(@"^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1}[\da-zA-Z-]{2,3}$", ErrorMessage = "Please enter valid email address")]
        public string Email { get; set; }
    }
    [MetadataType(typeof(SampleClassMetaData))]
    public partial class SampleClass
    {      
    }


No comments:

Post a Comment