主键和唯一键单独异常处理| asp .net c#

时间:2015-03-26 17:51:59

标签: c# sql asp.net sql-server

我正在使用以下代码来处理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.

请为此提出任何解决方案。

1 个答案:

答案 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.
}