DbEntityValidationException
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);
}
}
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();
}
}
thank you @davidroth ... i will give it a shot...
Where is the ValidationResult class from?
@chaim1221
System.ComponentModel.Annotations
try
{
db.SaveChanges();
}
catch (DbUpdateException e)
{
// TODO: catch EF core Exception
}
catch { }