Home > Enterprise >  Where is UpdateException in EF Core?
Where is UpdateException in EF Core?

Time:11-20

I'm porting my old EF6 code to EF Core and I'm encountering the problem where UpdateException is not found in the following code:

internal void SetErrors(DbUpdateException ex)
{
    databaseErrors.Clear();

    if (!(ex.InnerException is UpdateException) ||
        !(ex.InnerException.InnerException is SqlException))
        return;

    var sqlException = (SqlException)ex.InnerException.InnerException;

    for (int i = 0; i < sqlException.Errors.Count; i  )
    {
        var sqlError = sqlException.Errors[i];

        if (databaseErrors.ContainsKey(sqlError.Number))
            continue;

        if (!string.IsNullOrWhiteSpace(sqlError.Procedure))
        {
            databaseErrors.Add(sqlError.Number, string.Format("{0}: {1}", sqlError.Procedure, sqlError.Message));
        }
        else
        {
            databaseErrors.Add(sqlError.Number, sqlError.Message);
        }
    }
}

Intellisense suggests System.Data so I added that namespace but it is still not found. So where can I find this class?

CodePudding user response:

It's gone. Removed. Vanished. Replaced. Pining for the fjords. It is a dead exception type. It is an ex-exception.

Observe that enter image description here


The Microsoft.EntityFrameworkCore.DbUpdateException replaces it: the Entries collection property is the analog of UpdateException.StateEntries.

There is no guarantee that DbUpdateException.InnerException will be a SqlException. If you do want to check InnerException then do it in a loop, rather than only checking 1 or 2 levels deep:

static SqlException? GetFirstInnerSqlExceptionOrNull( Exception? ex )
{
    while( ex != null )
    {
        if( ex is SqlException sqlEx ) return sqlEx;
        ex = ex.InnerException;
    }

    return null;
}

Usage (given your code post):

internal void SetErrors( DbUpdateException ex )
{
    if( GetFirstInnerSqlExceptionOrNull( ex ) is SqlException sqlEx )
    {
        foreach( SqlError err in sqlEx.Errors )
        {
            // stuff
        }
    }
    

}
  • Related