從數據庫中刪除一條記錄時,偶爾我會碰到參考約束異常。有沒有辦法在C#中測試特定的SQL異常類型?
這裏是例外的細節。當異常特別與外鍵約束錯誤有關時,是否可以向用戶顯示消息?
我可以看看異常錯誤字符串並測試一個單詞的存在,但我不確定是否有更好的方法來檢查特定的SQL錯誤。
感謝 凱文
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)
您需要檢查整個['Errors'](http://msdn.microsoft .com/en-us/library/system.data.sqlclient.sqlexception.errors.aspx)數組,因爲單個批處理(SQL請求)可能返回多個錯誤。 –
@RemusRusanu,謝謝你指出這一點。我已經更新了我的答案以包含這些有價值的信息。 –
以下是錯誤代碼列表http://msdn.microsoft.com/en-us/library/cc645603(SQL.105).aspx –