Is it possible to define error message for UNIQUE KEY constraint in SQL SERVER when it is called by EF 4.0?

六月ゝ 毕业季﹏ 提交于 2019-12-14 03:58:15

问题


I don't need to execute duplicatation query like checking some column is unique or not because this operation always execute with SQL Server constraint. However, default error message from SQL Server is not well-defined for end-user.

Do you have any idea for change/redefine error message to be more user-friendly?

PS. I execute all query via Entity Framework 4.0.


回答1:


The only way I know to do this is to catch SqlException and then check the Number property. This property is a short-cut to the first Error in the Errors property, and if you are worried about the possiblity of multiple error conditions, you could use that instead.

Once you know the sql error number, you can provide a more user-friendly message. Unfortunately, I do not know of a way to get a nice list of common sql server error numbers, besides doing select * from sys.messages, but it can be a little overwhelming to search through them.

I only cared about a few specific error numbers and created the error conditions manually to determine the numbers:

 547 foreign key conflict
2601 unique index violation
2627 primary key violation

On any other error number, I just provide a generic message indicating that there was a problem with the database. In all cases, I log the exception information for later use (using NLog).



来源:https://stackoverflow.com/questions/8440310/is-it-possible-to-define-error-message-for-unique-key-constraint-in-sql-server-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!