Click here to Skip to main content
14,602,962 members

Basic Introduction to Data Annotation in .NET Framework

Rate this:
4.93 (29 votes)
Please Sign up or sign in to vote.
4.93 (29 votes)
6 Oct 2014CPOL
Basic introduction to Data Annotation in .NET Framework


Data Annotation in .NET Framework means add extra meaning to the data by adding attribute tags. The advantage of using Data Annotation feature is that by applying Data Attributes, we can manage the data definition in a single place and do not need re-write the same rules in multiple places.

The Data Annotation feature got introduced in .NET 3.5 and the System.ComponentModel.DataAnnotations namespace contains the classes that are used as data attributes.

The Data Annotation attributes falls into three categories:

  1. Validation Attributes: Used to enforce validation rules.
  2. Display Attributes: Used to specify how data from a class /member is displayed in the UI.
  3. Modelling Attributes: Used to specify the intended use of class member and the relationship between classes.

Here in this article, I will be walking through the basic steps involved in implementing the Data Annotation feature. I am using Visual Studio Express 2013 for Desktop as my development environment targeting .NET framework 4.5.

First we will be creating our Data class, let's call it Employee. The requirement says Employee class should have properties like Name, Age, Email and Phone Number with the below criteria.

  • Name cannot be blank and should be of 3 characters minimum and 100 maximum characters.
  • Age should be between 18 and 99.
  • Email and Phone number should hold the respective data type validations.

Note: This is only a sample intended to demonstrate the .NET Data Annotation feature. I will be using some of the basic Data Annotation attributes and for more details on data annotation attribute, please refer to the Data Annotation documentation.

To implement the above requirement, we need to code in the UI layer to accommodate/validate the above criteria. The disadvantage is that if are using the Employee class in multiple places, we need to re-write the validation logic creating duplicate code which is not a good practice.

Here comes the beauty of .NET Data Annotation feature. We add Data Annotation attributes to the Employee class properties and the .NET framework takes care of the validation/display for us. We can add custom error messages as part of Data Annotation attribute.

Step 1

Create an empty solution as below. This will help us to add more Projects later.

Image 1

Step 2

Next create a class library project to hold Employee class as below to the solution.

Image 2

Add a class named Employee.cs and add reference to System.ComponentModel.DataAnnotations assembly to utilize the Data Annotation feature as below:

Image 3

Step 3

To allow the usage of types in System.ComponentModel.DataAnnotations, add the below code to Employee.cs.

using System.ComponentModel.DataAnnotations;

Image 4

Step 4

Add the below properties to the Employee class with the respective Data Annotation attributes.

public class Employee
        [Required (ErrorMessage="Employee {0} is required")]
        [StringLength (100,MinimumLength=3,
        ErrorMessage="Name Should be minimum 3 characters and a maximum of 100 characters")]
        public string Name { get; set; }

        [Range(18,99, ErrorMessage="Age should be between 18 and 99")]
        public int Age { get; set; }

        Public string PhoneNumber { get; set; }

        Public string Email { get; set; }

Image 5

Step 5

Testing the Employee class Data Validation using a Console Application.

Create a new Console Application project and add reference to Employee class library and System.ComponentModel.DataAnnotations assembly.

Our Solution explorer looks as below:

Image 6

Step 6

To allow the usage of types in System.ComponentModel.DataAnnotations and Employee class, add the below code to Program.cs:

using Model.Employee;
using System.ComponentModel.DataAnnotations;

namespace TestEmployeeValidation
    class Program
        static void Main(string[] args)
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Employee class Validation");

            Employee objEmployee = new Employee ();
            objEmployee.Name = "sa";
            objEmployee.Age = 12;
            objEmployee.PhoneNumber = "1234as";
            objEmployee.Email = "test@re";

            ValidationContext context = new ValidationContext(objEmployee, null, null);
            List<ValidationResult> results = new List<ValidationResult>();
            bool valid = Validator.TryValidateObject(objEmployee, context, results, true);

            if (!valid)
                foreach (ValidationResult vr in results)
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.Write("Member Name :{0}", vr.MemberNames.First());
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("   ::  {0}{1}", vr.ErrorMessage, Environment.NewLine);

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("\nPress any key to exit");

Hit F5 (or whatever you have configured your debug key in Visual Studio) to validate Employee class.

Now, we can see the validation details as below in the Console Window displaying Validation errors based on the Data Annotation attributes added to Employee class.

Image 7

Here, the advantage of using Data Annotation attributes is that now if we want to reuse the Employee class in an ASP.NET MVC application or Windows Forms Application, we can still use the same validation without writing any extra piece of Validation code.

This is just a beginner article on how to use .NET Data Annotation. Please refer to the Data Annotation documentation for more details on Data Annotation attribute and its capabilities.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mathew Soji
Software Developer
India India
No Biography provided

Comments and Discussions

QuestionVery useful!!! Pin
Cheung Tat Ming12-Oct-14 6:32
MemberCheung Tat Ming12-Oct-14 6:32 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun10-Oct-14 1:45
MemberHumayun Kabir Mamun10-Oct-14 1:45 
QuestionGlobalization Pin
Member 32560317-Oct-14 2:08
professionalMember 32560317-Oct-14 2:08 
AnswerRe: Globalization Pin
xondokan7-Oct-14 2:45
Memberxondokan7-Oct-14 2:45 
GeneralRe: Globalization Pin
Member 32560317-Oct-14 3:00
professionalMember 32560317-Oct-14 3:00 
GeneralRe: Globalization Pin
xondokan7-Oct-14 3:36
Memberxondokan7-Oct-14 3:36 
GeneralRe: Globalization Pin
dmjm-h7-Oct-14 12:13
Memberdmjm-h7-Oct-14 12:13 
AnswerRe: Globalization Pin
Mathew Soji7-Oct-14 3:38
professionalMathew Soji7-Oct-14 3:38 
AnswerRe: Globalization Pin
Mathew Soji7-Oct-14 3:41
professionalMathew Soji7-Oct-14 3:41 
AnswerRe: Globalization Pin
Mathew Soji16-Oct-14 1:08
professionalMathew Soji16-Oct-14 1:08 
GeneralRe: Globalization Pin
Member 325603116-Oct-14 1:26
professionalMember 325603116-Oct-14 1:26 
QuestionNice introduction to Data Annotation in .NET Framework Pin
Volynsky Alex6-Oct-14 10:41
professionalVolynsky Alex6-Oct-14 10:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 6 Oct 2014


46 bookmarked