Entity Framework Core DbUpdateException detailed information

c# entity-framework-core integration-testing

Popular Answer

In fact, EF7 lacks the validation that EF6 offers. Given that validation is presumpted before models are submitted to be stored, this seems to be a design decision (and also DB constraints might be used as a safety net).

Before storing data, This piece demonstrates how to manually carry out validations. Be aware that this only works for data annotation. Here is my somewhat modified version:

public void Validate()
{
    var entities = ChangeTracker.Entries()
        .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified)
        .Select(e => e.Entity)
        .ToList();

    foreach (var entity in entities)
    {
        var validationContext = new ValidationContext(entity);
        Validator.ValidateObject(entity, validationContext, validateAllProperties: true);
    }
}

My recommendation is to include a method to handle both validation and database exceptions, along the lines of:

try
{
    Validate();
    Context.SaveChanges();
}
catch(ValidationException exc)
{
    Logger.LogError(exc, $"{nameof(SaveChanges)} validation exception: {exc?.Message}");
    return false;
}
catch (DbUpdateException exc)
{
    Logger.LogError(exc, $"{nameof(SaveChanges)} db update error: {exc?.InnerException?.Message}");
    return false;
}
0
6/4/2018 2:20:16 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow