c# - 有没有办法在 C# 中测试特定的 sql 异常类型?

标签 c# asp.net sql-server

从数据库中删除记录时,偶尔会遇到引用约束异常。

这里是异常的详细信息。当异常与外键约束错误具体相关时,是否可以向用户显示消息?

我可以查看异常错误字符串并测试单词是否存在,但我不确定是否有更好的方法来检查特定的 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)

最佳答案

Is it possible to display a message to the user when the exception is specifically related to a foreign key constraint error?

是的,您可以检查 Number 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.
    }
}

如评论部分所述,最好检查 Errors数组,因为可能存在与单个 SQL 查询相关的多个错误。

关于c# - 有没有办法在 C# 中测试特定的 sql 异常类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11191110/

相关文章:

c# - 可选参数和方法重载

c# - 在实现具有同步和异步 API 的库以实现相同功能时使用 async await

c# - 动态 linq 和运算符重载

c# - ASP.NET MVC Razor : Add empty value to a DropDownList

c# - 如何选择列包含字符串的任何单词的所有行

asp.net - 为什么 IIS Express 使用 <system.web> 而不是 <system.webServer>?

C# ASP.NET MVC 资源文件的字符串在 HTML 源中是一种奇怪的编码格式

sql - 如果所有表中不存在某列,是否添加该列?

sql-server - SQL Server 标识主键与无标识性能 - 在主键中使用公式

c# - 启动 SQL Server 导入/导出向导?