[Entity Framework] DBContext API – Validation API (2) – Validating Multiple Entities

Validating a single entity object is is quite useful in a web applications. In most web applications, the entity object is processed as soon as it is added or modified. But in some applications, the batch processing can be a better option. In a batch mode, you need to deal with multiple entity objects.

 

1. Validating Multiple Objects

The “DbContext” class has the “GetValidationErrors()” method to validate “Added” and “Modified” objects in the context. It returns a collection of “DbEntityValidationResult” objects.

public class DbContext
{
  public IEnumerable<DbEntityValidationResult> GetValidationErrors();
}

Before validating entities, the “GetValidationErrors()” calls the “DetectChanges()“.

 

2. Data Annotations

Let’s validate 2 entities.

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

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

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

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

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

public static class ValidationTest
{
  public static void DoValidation()
  {
    MyCategory c = new MyCategory { Id = 1, Name = "Toy" }; // Valid
    MyProduct p = new MyProduct { Id=1, Name = ""};

    using (MyProductContext context = new MyProductContext())
    {
      context.Categories.Add(c);
      context.Products.Add(p);

      c.Name = "Long Name"; // Invalid

      foreach (DbEntityValidationResult result in context.GetValidationErrors())
      {
        Console.WriteLine("{0} is Valid? {1}", result.Entry.Entity.ToString(), result.IsValid);

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

The output is like this:

MyCategory is Valid ? False
Name: Category Name should be less than 5 characters.
MyProduct is Valid ? False
Name: The product name is required

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