Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch REFERENCE constraint exception from SQL in C#

What will be proper way to catch exception which throw SQL server when I deleting data with Reference constraint from C# code.
I want to show my users message like:
"I can't delete the data because is used"
, rather than of showing message like this:

The DELETE statement conflicted with the REFERENCE constraint ... The conflict ccurred*in database "rampa", table "dbo.doc", column 'kartica_id'.
like image 506
adopilot Avatar asked Jul 01 '26 10:07

adopilot


1 Answers

Use this:

try
{
   //Execute delete statement
}
catch (SqlException sqlEx)
{
   //Handle exception
}
finally
{
   //Close connection
}

All sql errors are thrown as SqlException and there are no specific errors. To find out what was error exactly, there is property SqlException.Number which is the same as SQL Error Code. You can find the list of codes here.

like image 154
Ivan Ferić Avatar answered Jul 02 '26 22:07

Ivan Ferić