efcore icon indicating copy to clipboard operation
efcore copied to clipboard

DbEntityValidationException

Open giancarloa opened this issue 10 years ago • 5 comments

Hi... in EF6 I had the code below that overrides the DbContext SaveChanges method... the code basically catches a DbEntityValidationException and does some manipulation of the error messages it exposes... I am having trouble porting this over to EF7... I don't see DbEntityValidationException is available... any ideas on how to convert this code to EF7???? thank you

        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);
                throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors);
            }
        }

giancarloa avatar Jan 29 '16 18:01 giancarloa

In EFCore (former EF7), there is no build in entity validation. As a result there is no DbEntityValidationException class.

If you want to keep the validation behavior known in EF6, you have to implement it yourself. However, this is as trivial as applying the following lines of code to SaveChanges:

public class YourDbContext : DbContext
{
    public override int SaveChanges()
    {
       var entities = (from entry in ChangeTracker.Entries()
              where entry.State == EntityState.Modified || entry.State == EntityState.Added
              select entry.Entity);

       var validationResults = new List<ValidationResult>();
       foreach (var entity in entities)
       {
           if(!Validator.TryValidateObject(entity, new ValidationContext(entity), validationResults))
           {
               // throw new ValidationException() or do whatever you want
           }
       }                    
       return base.SaveChanges();
    }
}

davidroth avatar Jan 30 '16 13:01 davidroth

thank you @davidroth ... i will give it a shot...

giancarloa avatar Feb 01 '16 18:02 giancarloa

Where is the ValidationResult class from?

chaim1221 avatar Nov 21 '18 05:11 chaim1221

@chaim1221

System.ComponentModel.Annotations

davidroth avatar Nov 22 '18 13:11 davidroth

try
{
     db.SaveChanges();
}
catch (DbUpdateException e)
{
    // TODO: catch EF core Exception
}
catch { }

zanyar3 avatar Aug 07 '22 07:08 zanyar3