EF Core - A way to get the data that is updating on SaveChangesAsync() RRS feed

  • Question

  • User-1188570427 posted

    Is there a way (say if an error occurs) to get the data that has failed on a DbUpdateException from the context object?

    I tried something like the below, but it always has 0 records found:

        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();


                   var modifiedEntries = biContext.ChangeTracker
                                           .Where(x => x.State == EntityState.Modified)
                                           .Select(x => x.Entity)
                    foreach (var eve in modifiedEntries)
                        sb.AppendLine("Info: " + eve.ToString());

    Wednesday, September 19, 2018 8:34 PM

All replies

  • User283571144 posted

    Hi tvb2727,

    As far as I know, there are four possible checks that can be applied to data before it is written to the database. Three of these are inside EF and are easy to set up while the last one involved capturing errors reported by the underlying database.

    • Data Annotations, e.g. [MinLength(100)] to check the length of a string.
    • IValidatableObject. This is a method where to can code your own checks.
    • ValidateEntity. A DbContext method that allows access to the database while checking.
    • DbUpdateException Capturing database-generated errors

    So I suggest you could follow below article to know how to catch the  bad data in EF core.

    More details, you could refer to below article.


    Best Regards,


    Thursday, September 20, 2018 7:17 AM