Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

sql server - Entity Framework: How to properly handle exceptions that occur due to SQL constraints

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'.
The statement has been terminated."

How do I properly catch this specific exception?

Dirty solution:

    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:

  • No type safety: The code depends on the exception message which contains the name of the unique column.
  • Dependency on the SqlCLient classes (broken abstraction)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...