private static IStatusGeneric ExecuteValidation(this DbContext context) { var status = new StatusGenericHandler(); var entriesToCheck = context.ChangeTracker.Entries() .Where(e => (e.State == EntityState.Added) || (e.State == EntityState.Modified)).ToList(); //This is needed, otherwise you get a "collection has changed" exception foreach (var entry in entriesToCheck) { var entity = entry.Entity; status.Header = entity.GetType().GetNameForClass(); var valProvider = new ValidationDbContextServiceProvider(context); var valContext = new ValidationContext(entity, valProvider, null); var entityErrors = new List <ValidationResult>(); if (!Validator.TryValidateObject( entity, valContext, entityErrors, true)) { status.AddValidationResults(entityErrors); } } status.Header = null; //reset the header, as could cause incorrect error message return(status); }
private static IStatusGeneric ExecuteValidation(this DbContext context) { var status = new StatusGenericHandler(); foreach (var entry in context.ChangeTracker.Entries() .Where(e => (e.State == EntityState.Added) || (e.State == EntityState.Modified))) { var entity = entry.Entity; status.Header = entity.GetType().GetNameForClass(); var valProvider = new ValidationDbContextServiceProvider(context); var valContext = new ValidationContext(entity, valProvider, null); var entityErrors = new List <ValidationResult>(); if (!Validator.TryValidateObject( entity, valContext, entityErrors, true)) { status.AddValidationResults(entityErrors); } } return(status); }