Reputation: 452
I am using following code to handle exceptions for Unique key and primary key violation.
catch (SqlException ex)
{
if (ex.Number == 2627)
{
if (ex.Message.Contains("Unique"))
//error msg regarding Unique key violation.
else
//error msg regarding Primary key violation.
}
else
//any other error msg.
}
But it is not working properly. For both primary key and unique key violation same error message (error msg of primary key) displays.
When I simply display error messages whithout using
if (ex.Number == 2627)
{
if (ex.Message.Contains("Unique"))
//error msg regarding Unique key violation.
else
//error msg regarding Primary key violation.
}
else
following error messages are shown:
For Primary key:
Violation of PRIMARY KEY constraint 'PK_users'. Cannot insert duplicate key in object 'dbo.users'. The statement has been terminated.
and
For Unique key:
Violation of UNIQUE KEY constraint 'UQ__users__AB6E61640425A276'. Cannot insert duplicate key in object 'dbo.users'. The statement has been terminated.
Please suggest any solution for this.
Upvotes: 3
Views: 3791
Reputation: 5771
The Contains method is case sensitive. You should be using
catch (SqlException ex)
{
if (ex.Number == 2627)
{
if (ex.Message.Contains("UNIQUE"))
//error msg regarding Unique key violation.
else
//error msg regarding Primary key violation.
}
else
//any other error msg.
}
Upvotes: 4