Simple Entity Framework Data Validation Example

In a previous example we explored validation options using Data Annotations. We decorate our domain class properties with some basic validation rules like Required, MaxLength, Range and so on. When we make a call to the DbContext SaveChanges method, these validation rules are applied to the properties about to be saved, preventing faulty data to get to our database.

In this example we take a first look at what validation exception Entity Framework throws and how to retrieve the property specific information on these errors. We have a basic EmailUser poco class with an Id, Name and Address property. The Name property is required and must be at least five characters long. The Address property is also required and must be a valid email address verified by using a regular expression pattern.

using System.ComponentModel.DataAnnotations;
 
namespace CodeFirstMail.Pocos
{
    public class EmailUser : IEntity
    {
        private const string RegExEmailPattern =
            @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$";
 
        public int Id { get; set; }
 
        [Required, MinLength(5)]
        public string Name { get; set; }
 
        [Required, RegularExpression(RegExEmailPattern)]
        public string Address { get; set; }
    }
}

We write a test to see what happens when the validation requirements aren’t met. We make some obvious mistakes in the EmailUser object for both Name and Address.

using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using CodeFirstMail.Context;
using CodeFirstMail.Pocos;
using Microsoft.VisualStudio.TestTools.UnitTesting;
 
namespace CodeFirstTests
{
    [TestClass]
    public class MailContextTest
    {
        [TestMethod]
        [ExpectedException(typeof (DbEntityValidationException))]
        public void EntityValidationShouldThrowDbEntityValidationException()
        {
            Database.SetInitializer(
                new DropCreateDatabaseIfModelChanges<MailContext>());
 
            using (var mailContext = new MailContext())
            {
                try
                {
                    var userManon =
                        new EmailUser
                            {
                                Name = "Mnon",                  // too short
                                Address = "manon@bussel..net"   // double dot
                            };
 
                    mailContext.EmailUsers.Add(userManon);
                    mailContext.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    LogValidationErrors(ex);
                    throw;
                }
            }
        }

We expect (and in fact wrongly assume) an exception of type DbEntityValidationException to be thrown. In the LogValidationErrors method we write all validation errors to the Debug output.

        private static void LogValidationErrors(DbEntityValidationException ex)
        {
            foreach (DbEntityValidationResult validation 
                in ex.EntityValidationErrors)
            {
                Debug.WriteLine(
                    "Error in entity {0}",
                    validation.Entry.Entity);
 
                foreach (DbValidationError propertyError 
                    in validation.ValidationErrors)
                {
                    Debug.WriteLine(
                        "Error in property {0}: {1}",
                        propertyError.PropertyName,
                        propertyError.ErrorMessage);
                }
            }
        }
    }
}

We run our test and indeed get the two validation errors for the Name and Address properties with some default error description. Not very useful to present to our users of course, but very handy while developing.

  • Error in entity CodeFirstMail.Pocos.EmailUser
  • Error in property Name: The field Name must be a string or array type with a minimum length of ’5′.
  • Error in property Address: The field Address must match the regular expression ‘^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$’.

Entity Framework Data Validation Test

That’s basically it. In upcoming examples we explore more advanced issues of Entity Framework Data Validation.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>