When deleting a record from the database, occasionally I will run into a reference constraint exception.
Here are the exception details. Is it possible to display a message to the user when the exception is specifically related to a foreign key constraint error?
I can look at the exception error string and test for the existence of a word, but I wasn't sure if there is a better way to check for a specific SQL error.
Thanks Kevin
Message: The DELETE statement conflicted with the REFERENCE constraint "FK_Customers_PaymentTerms". The conflict occurred in database "kd", table "dbo.Customers", column 'CstPtmID'.
The statement has been terminated.
Source: .Net SqlClient Data Provider
TargetSite: Void OnError(System.Data.SqlClient.SqlException, Boolean)
StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
Is it possible to display a message to the user when the exception is specifically related to a foreign key constraint error?
Yes, you could check the Number
of the SqlException:
try
{
// do your database query
}
catch (SqlException ex)
{
if (ex.Number == .....)
{
// Can't remember from the top of my head the exact error code
// that is triggered in this situation. Just check it.
}
}
As explained in the comments section, it is better to check the Errors
array because there might be multiple errors related to a single SQL query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With