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

dri*_*iAn 17 sql sql-server entity-framework constraints unique-constraint

我使用Entity Framework来访问我的SQL数据.我在数据库模式中有一些约束,我想知道如何处理由这些约束引起的异常.

例如,在两个用户尝试同时向DB添加(几乎)相同的实体的情况下,我得到以下异常.

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."
Run Code Online (Sandbox Code Playgroud)

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

脏的解决方案:

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在虽然这种方法有效,但它有一些缺点:

  • 无类型安全:代码取决于包含唯一列名称的异常消息.
  • 对SqlCLient类的依赖(破坏抽象)

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

注意:我不想在应用程序层中手动编写约束,我想将它们放在数据库中.

gbn*_*gbn 17

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

在这种情况下,它是2627,对于SQL Server来说是永远相同的.

如果你想要抽象,那么你总是会对数据库引擎有一些依赖,因为每个引擎都会抛出不同的异常数和消息.