How to handle duplicate value Exception in Entity Framework?

c# ef-code-first entity-framework-6

Question

I have a Users model class which has UserID as primary key. I want to handle the exception if duplicate value for UserID (primary key) is inserted and display a proper message to the user.

I tried to handle exception by using

try 
{
    db.SaveChanges();
}
catch (Exception ex)
{
    var sqlException = ex.InnerException as SqlException;

    if (sqlException.Number == 2627 || sqlException.Number == 2601 ) 
        MessageBox.Show("User already exists");
}

but this didn't work as VS 2015 throws the null exception error.

Here is my Users model class

class Users
{
        [Key]
        [MaxLength(10), MinLength(5)]
        public string userID { get; set; }

        [Required]
        [MaxLength(20)]
        public string password { get; set; }

        public bool isAdmin { get; set; }
}
1
0
7/21/2019 7:02:28 AM

Popular Answer

The null reference exception is raised because the first inner exception is not a SqlException. What you get is a DbUpdateException, its inner exception is an UpdateException and this exception's inner exception is a SqlException.

You have to traverse the inner exceptions until you find the SqlException, for which you can use this method:

public TException GetInnerException<TException>(Exception exception)
    where TException : Exception
{
    Exception innerException = exception;
    while (innerException != null) 
    {
        if (innerException is TException result)
        {
            return result;
        }
        innerException = innerException.InnerException;
    }
    return null;
}

Which turns your code into:

catch (DbUpdateException ex) // catch DbUpdateException explicitly
{
    var sqlException = GetInnerException<SqlException>(ex);

    if (sqlException != null 
        && (sqlException.Number == 2627 || sqlException.Number == 2601) )
    {
        MessageBox.Show("User already exists");
    }
}
1
7/23/2019 8:47:42 AM


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