Learn How to Validate Your Entities in the Entity Framework

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

As entity framework has become an essential part of modern day data driven applications and ASP.NET MVC applications, it is important to know the bits and pieces of it. In this article I will explain about the validation techniques that can be used in ADO.NET Entity Framework 4.1 to validate the model data. ADO.NET Entity Framework 4.1 version does not come with .Net framework 4.0, rather it is available as a separate download which can be downloaded from here.

Code First Development Pattern - POCO

The development patterns, which were available in the previous versions of the ADO.NET Entity Framework, are model first and database first.

1. Model first is the pattern where a conceptual model is defined using .edmx file and from there the database is created.

2. Database first is the pattern where the database is created and the model is generated from the database schema.

When a developer is asked about the disadvantage of the above patterns, the straight answer would be the auto generated code. Even if you do some changes or add some custom validation in the auto generated designer code, it would be overwritten during refresh. ADO.NET Entity Framework 4.1 comes with a Code First development pattern where you can create independent POCO (Plain Old CLR Objects) classes. The POCO classes will contain the properties that will be mapped to the database columns. Below is a sample POCO class to initiate a code first entity framework development.

namespace EntityValidationSample.POCOS
{
    public class Employee
    {
        public int ID { get; set; }
        public string EmployeeName { get; set; }
        public int Age { get; set; }
        public string Department { get; set; }
        public int Salary { get; set; }
    }
}

Creating the Database Context

The database context can be created by inheriting your custom context class from DbContext class. DbContext is available in the namespace System.Data.Entity.

namespace EntityValidationSample
{
    public class MyDatabaseContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
}

Validation Techniques

Once the code first entity classes are created, it becomes important to validate the data to be injected into it. In this section let us see various ways of performing validation in ADO.NET Entity Framework 4.1.

DataAnnotations

Data annotations are nothing but a certain set of attributes that can decorate the POCO classes and its properties. Below are some of the main data annotations used for performing data validation.

1. Required - This is used to mark the property as a required field.

2. DataType - To validate a property value for a particular data type.

3. StringLength - To validate for both minimum and maximum length of the string.

These attributes are part of the library System.ComponentModel.DataAnnotations.

namespace EntityValidationSample.POCOS
{
    public class Employee
    {
        public int ID { get; set; }
        [Required(ErrorMessage="EmployeeName is required")]
        public string EmployeeName { get; set; }
        [Required(ErrorMessage="Age is required")]
        public int Age { get; set; }
        [StringLength(100, MinimumLength=50, ErrorMessage="Department Name should be between 50 and 100 characters")]
        public string Department { get; set; }
        [DataType(DataType.EmailAddress, ErrorMessage = "Email address is not valid")]
        public string Email { get; set; }
        public int Salary { get; set; }
    }
}
 

When using data annotations in ASP.NET MVC application, the validation can be switched to the client side.

Code First Fluent API

Code first fluent API is used to override the existing data annotations. This can be implemented by overriding the method OnModelCreating of the DbContext class. I did not find a way to provide the error messages while performing validations through the fluent API.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>().Property(p => p.EmployeeName).HasMaxLength(100);
}
 

In one of the MSDN blogs it has been advised to use Data Annotations over the fluent API for validation purposes.

Doing Custom Validations

ADO.NET Entity framework also allows the developer to add custom validations. This can be done in two ways.

1. Implementing the Validate method of the IValidatable interface in the POCO class.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> result = new List<ValidationResult>();
 
            //Validate and add the validation result to the list
            return result;
        }
 

2.Overriding ValidateEntity method of the DbContext class.

Note: All of the above mentioned validations will be triggered when the database context's SaveChanges method is called.

Happy reading!



About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Related Articles

Comments

  • india walkins

    Posted by india walkins on 02/20/2013 03:41am

    Very nice one. Thank You.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date