What to use instead DbEntityValidationException in EF Core?
Asked Answered
M

2

15

With EF I used DbEntityValidationException catch branch (along with others)

catch (DbEntityValidationException exception)
{
    // any statements here...
    throw;
}

Now using .NET Core 3.17 with EF Core 3.17 and apparently there is no DbEntityValidationException and also reviewed EF Core 3.17 sources, and no traces of that exception type. (Note, I am not only talking about where it is defined, I mean it is not thrown any places in the EF Core 3.17 sources)

Question

How to migrate the code above to EF Core 3.17?

Mispleading answered 8/9, 2020 at 11:56 Comment(3)
DbUpdateException is likely what you're after.Atalie
thx, going to examineMispleading
Note that DbUpdateException does not have collection of exceptions(probably intentionally)Reportorial
C
2

When you look at the documentation for DbEntityValidationException, you can see the versions it applies to are only: 4.3.1, 5.0.0, 6.2.0.

Now if you look at the docs for SaveChanges (assuming that's what you're calling inside your try block, you can see that it now only throws DpUpdateException and DbUpdateConcurrencyException. So I think what you probably want is the below, since that should catch any exception while saving to the db. I'd think validation would be included in that.

catch (DbUpdateException exception)
{
    // any statements here...
    throw;
}
Cliff answered 6/4, 2023 at 19:25 Comment(0)
G
2

Model validation on save is gone from EF core. This is a quote from EF developers:

Validation happens on the client, then again in the action to protect against malicious requests. Most validation also happens in the database too (nullability of columns, max length of data, etc.). Obviously not all apps go that far, but validating during SaveChanges is usually just front loading an exception you would get from the database and adding overhead to do that.

Said that, if you deem you need it one more, your objects could implement IValidatableObject and that interface could be used by overriding SaveChanges:

public override int SaveChanges() {
    var validationErrors = ChangeTracker
        .Entries<IValidatableObject>()
        .SelectMany(e => e.Entity.Validate(null))
        .Where(r => r != ValidationResult.Success);

    if (validationErrors.Any()) {
       // Possibly throw an exception here
    }

   return base.SaveChanges();
}

See also: https://long2know.com/2016/07/porting-ef6-to-ef7-or-ef-core/

Gascony answered 3/8, 2023 at 7:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.