Saad A
Saad A

Reputation: 1147

DbEntityValidationException without DRY

I am using "EF Designer from Database" in my ASP.NET MVC project for CRUD functionality.

I have quite a few actions that deal with CRUD functionality and I wish validate when saveChanges() method is called and try and catch if any error where thrown.

try
{
      db.SaveChanges();
}
catch (DbEntityValidationException e)
{
     foreach (var eve in e.EntityValidationErrors)
     {
        Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State);

        foreach (var ve in eve.ValidationErrors)
        {
              Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
       }
    }

 }

Currently the above code is repeated in several action methods, I was wondering if there is a cleaner way of doing this without repeating the same code? Is there a design pattern for this type work?

Upvotes: 0

Views: 111

Answers (1)

Daniel Lorenz
Daniel Lorenz

Reputation: 4336

In your specific DbContext, just override SaveChanges() and do this:

public class MyDbContext : DbContext 
{
...
public override int SaveChanges()
    try
{
      base.SaveChanges();
}
catch (DbEntityValidationException e)
{
 foreach (var eve in e.EntityValidationErrors)
 {
    Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State);

    foreach (var ve in eve.ValidationErrors)
    {
          Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
   }
}

}

Upvotes: 1

Related Questions