admin

实体框架:如何正确处理由于SQL约束而发生的异常

sql

我使用实体框架访问我​​的SQL数据。我在数据库模式中有一些约束,我想知道如何处理由这些约束引起的异常。

例如,当两个用户尝试同时向数据库添加(几乎)相同的实体时,出现以下异常。

System.Data.UpdateException
"An error occurred while updating the entries. See the InnerException for details."

(inner exception) System.Data.SqlClient.SqlException
"Violation of UNIQUE KEY constraint 'Unique_GiftId'. Cannot insert duplicate key in object 'dbo.Donations'.\r\nThe statement has been terminated."

如何正确捕获此特定异常?

肮脏的解决方案:

    catch (UpdateException ex)
    {
        SqlException innerException = ex.InnerException as SqlException;
        if (innerException != null && innerException.Message.StartsWith("Violation of UNIQUE KEY constraint 'Unique_GiftId'"))
        {
            // handle exception here..
        }
        else
        {
            throw;
        }
    }

现在,尽管这种方法行之有效,但它也有一些缺点:

  • 没有类型安全性:该代码取决于包含唯一列名称的异常消息。
  • 对SqlCLient类的依赖(抽象中断)

您知道更好的解决方案吗?感谢您的所有反馈。

注意: 我不想在应用程序层中手动编写约束,而是希望将它们存储在数据库中。


阅读 161

收藏
2021-05-10

共1个答案

admin

您应该能够捕获SQL错误号(即SqlException.Number)。

在这种情况下,对于SQL Server来说永远是2627。

如果要抽象,则对数据库引擎总是有一定的依赖性,因为每个引擎都会抛出不同的异常号和消息。

2021-05-10