Learn How to Validate Your Entities in the Entity Framework

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!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read