Skip to content
Advertisement

How can I know if an SQLexception was thrown because of foreign key violation?

I want to tell the user that a record was not deleted because it has child data, but how can I be sure that the exception was thrown because of a foreign key violation? I see that there a sqlexception class that is used for all sql exception.

Advertisement

Answer

Assume you’re using SQL Server.

Using teh web archive – https://web.archive.org/web/20190120182351/https://blogs.msdn.microsoft.com/tomholl/2007/08/01/mapping-sql-server-errors-to-net-exceptions-the-fun-way/

Case 547 is your man.

UPDATE The above is sample code and should not be used. Please follow the link as to explain why.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement