Search code examples
c#entity-frameworkexception

Duplicate key exception from Entity Framework?


I'm trying to catch the exception thrown when I insert a already existing user with the given username into my database. As the title says then I'm using EF. The only exception that's thrown when I try to insert the user into to db is a "UpdateException" - How can I extract this exception to identify whether its a duplicate exception or something else?


Solution

  • catch (UpdateException ex)
    {
        SqlException innerException = ex.InnerException as SqlException;
        if (innerException != null && innerException.Number == ??????)
        {
            // handle exception here..
        }
        else
        {
            throw;
        }
    }
    

    Put the correct number at ?????? that corresponds to unique constraint violation (I don't know it from the top of my head).