开发者

Custom Exception in LINQ to SQL

开发者 https://www.devze.com 2023-03-14 17:09 出处:网络
I wan开发者_高级运维t to throw a custom exception when my Insert fails, which violates PK / FK relationship.

I wan开发者_高级运维t to throw a custom exception when my Insert fails, which violates PK / FK relationship. Now, LINQ TO SQL throws SQLException, I want to throw a more specific exception like CategoryException.


When you catch the SQLException you can check its Number property or navigate to its Errors property and check if it contains any SqlError with number 547 - that should be constraints violation. If you need details about what constraint was violated and on which table you must really parse the message as @tyrongower mentioned. The pattern for the message is:

The %ls statement conflicted with the %ls constraint "%.*ls". The conflict occurred in database "%.*ls", table "%.*ls"%ls%.*ls%ls.

Edit:

Depending on the type of application you are developing you should be aware of localization. SQL server can localize its error messages so if you deploy the application to the server using different locale setting your exception message parsing will not work.


You may need to catch the SQLException and parse the message body, then throw your desired custom exception.

0

精彩评论

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

关注公众号