开发者

How to get the Constraint Code that is shown in a Message property of thrown SqlException

开发者 https://www.devze.com 2023-02-20 20:29 出处:网络
Suppose I have a Exception Message like Violation of UNIQUE KEY constraint \'UC_FileTypeName\'. Cannot insert duplicate key in object \'dbo.FileUpload\'.

Suppose I have a Exception Message like

Violation of UNIQUE KEY constraint 'UC_FileTypeName'. Cannot insert duplicate key in object 'dbo.FileUpload'.  

Is there any class method or way to get the constraint named 'UC_FileTypeName' ? Since I was going to开发者_如何学C look up this constraint name in our database and show the descriptive message.

I was thinking of reading the the whole string and get the string that starts with 'UC' and ends with '. But I know there are other constraint error like 'FK_' etc, so its not a good idea.


Don't ever, under any circumstances, depend on parsing the Message property of an exception. In fact, don't ever depend on parsing any human-readable output.

It's not intended to be parsed. It's intended to be read by a human. Such messages can and do change based on changes in the current culture, and can change from release to release as grammar errors are corrected.

Even if you had the equivalent "friendly" message, do you really think your users can understand something like, "Sorry, you can't enter another row with the same A, B, and C columns as an existing row"?

Your best bet would be to validate your data first, and not even attempt to enter a row that would violate any constraints.

0

精彩评论

暂无评论...
验证码 换一张
取 消