实体框架:如何正确处理由于SQL约束而发生的异常 [英] Entity Framework: How to properly handle exceptions that occur due to SQL constraints

查看:353
本文介绍了实体框架:如何正确处理由于SQL约束而发生的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use Entity Framework to access my SQL data. I have some constraints in the database schema and I wonder how to handle exceptions that are caused by these constraints.

例如,在两个用户尝试同时向数据库添加(几乎)相同的实体。

As example, I get the following exception in a case where two users try to add an (almost) identical entity to the DB concurrently.

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."

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

How do I properly catch this specific exception?

脏解决方案

    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;
        }
    }

现在当这种方法工作时,它有一些缺点:

Now while this approach works, it has some downsides:


  • 没有类型安全:代码取决于包含唯一列名称的异常消息。

  • 对SqlCLient类的依赖性(破坏的抽象)

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

Do you know a better solution for this? Thanks for all feedback..

注意:我不想在应用程序层中手动编写约束,

Note: I do not want to code the constraints manually within the application layer, I want to have them in the DB.

推荐答案

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

You should be able to trap the SQL error number (which is SqlException.Number)

在这种情况下,它是2627,它一直是相同的SQL Server。

In this case it's 2627 which has been the same forever for SQL Server.

如果你想抽象,依赖于数据库引擎,因为每一个都会抛出不同的异常数字和消息。

If you want abstraction, then you'll always have some dependency on the database engine because each one will throw different exception numbers and messages.

这篇关于实体框架:如何正确处理由于SQL约束而发生的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆