我正在使用以下代码来处理Unique键和主键违规的异常。
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.
}
但它无法正常工作。对于主键和唯一键冲突,显示相同的错误消息(主键的错误消息)。
当我只是在不使用
时显示错误消息if (ex.Number == 2627)
{
if (ex.Message.Contains("Unique"))
//error msg regarding Unique key violation.
else
//error msg regarding Primary key violation.
}
else
显示以下错误消息:
For Primary key:
Violation of PRIMARY KEY constraint 'PK_users'. Cannot insert duplicate key in object 'dbo.users'. The statement has been terminated.
和
For Unique key:
Violation of UNIQUE KEY constraint 'UQ__users__AB6E61640425A276'. Cannot insert duplicate key in object 'dbo.users'. The statement has been terminated.
请为此提出任何解决方案。
答案 0 :(得分:3)
Contains方法区分大小写。你应该使用
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.
}