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

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

问题描述

我使用实体框架来访问我的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天全站免登陆