Custom Exception in LINQ to SQL

I want 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.

Answers


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.


Need Your Help

Route pattern matches but desired action Method is not getting called - Orchard 1.7

asp.net-mvc-4 orchardcms

I have a set of questions each having several tags to it. Each tag is clickable and supposed to filter the questions based on it.

How to create an email with embedded images that is compatible with the most mail clients

mime attachment embedded-resource

We have created a system that allows embedding an image in an outgoing email.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.