[Entity Framework] DBContext API – Validation API (1) – Validating a Single Entity

When you configure entity properties with data annotations or Fluent API, DbContext performs the validation of them. EF provides necessary types for validation and they are called Validation API.

 

1. Validating a Single Entity

The most basic operation of Validation API is to validate a single entity object.

public class DbContext
{
  public DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity);
}

DbContext has an “Entry<T>()” method to return the instance of “DbEntityEntry<T>“. This class provides access to information about the entity that is being tracked by the DbContext.

public class DbEntityEntry<TEntity>
{
  public DbEntityValidationResult GetValidationResult();
}

The “GetValidationResult()” method validates the entity and returns validation result.

public DbEntityValidationResult GetValidationResult(Product p)
{
  DbEntityValidationResult result;
  using (ProductContext context = new ProductContext())
  {
    result = context.Entry<Product>(p).GetValidationResult();
  }
  return result;
}

 

2.  DbEntityValidationResult Class

The “DbEntityValidationResult” class represents validation results for single entity. It is located in the “System.Data.Entity.Validation” namespace.

public class DbEntityValidationResult
{
  public bool IsValid { get; }
  public ICollection<DbValidationError> ValidationErrors { get; }
}

When the “IsValid” is false, you can look up the errors in the “ValidationErrors” collection.

public class DbValidationError
{
  public string ErrorMessage { get; }
  public string PropertyName { get; }
}

The “DbValidationError” object shows what is invalid.

 

3. Data Annotations

The following example shows how data annotations can be used with DbContext Validation API.

public class MyProduct
{
  public int Id { get; set; }

  [Required]
  public string Name { get; set; }

  [MaxLength(10)]
  public string Description { get; set; }
}

public class MyProductContext : DbContext
{
  public DbSet<MyProduct> Products { get; set; }
}

public static class ValidationTest
{
  public static void DoValidation()
  {
    MyProduct p = new MyProduct { Id=1, Name = "", Description = "Hello, World!" };

    using (MyProductContext context = new MyProductContext())
    {
      DbEntityValidationResult result = context.Entry<MyProduct>(p).GetValidationResult();

      Console.WriteLine("Valid: {0}", result.IsValid);

      foreach (DbValidationError e in result.ValidationErrors)
      {
        Console.WriteLine("{0}: {1}", e.PropertyName, e.ErrorMessage);
      }
    }
  }
}

When you run the application, you will get the following errors.

Valid: False
Name: The Name field is required.
Description: The field Description must be a string or array type with a maximum length of '10'.

When you use attributes to specify the rules, you can even provide error messages.

public class MyProduct
{
  public int Id { get; set; }

  [Required(ErrorMessage="The product name is required")]
  public string Name { get; set; }

  [MaxLength(10, ErrorMessage="Description should be less than 10 characters.")]
  public string Description { get; set; }
}

 

4. Fluent API

Fluent API is used to specify how the database is configured in Code First. It can also be used to validate data but there are some limitations.

Modify the entity and context classes.

public class MyProduct
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string Description { get; set; }
}

public class MyProductContext : DbContext
{
  public DbSet<MyProduct> Products { get; set; }

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<MyProduct>().Property(p => p.Name).IsRequired();
    modelBuilder.Entity<MyProduct>().Property(p => p.Description).HasMaxLength(10);
  }
}

When you run the application, you will get only one error (MaxLength). Also you cannot provide the custom error messages during the configuration.

[Note] If you want to configure database and validate data using Validation API, use data annotations.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s