如何在.NET CORE中使用SqlException?

Ali*_*eza 7 exception entity-framework-core asp.net-core ef-core-2.1

在我使用 .Net Framework 的旧项目中,使用

 using System.Data.SqlClient;
Run Code Online (Sandbox Code Playgroud)

if (ex.GetType() == typeof(SqlException))
{
    return ErrorMessage((SqlException)ex);
}
Run Code Online (Sandbox Code Playgroud)

现在在.NET CORE中不知道上面的代码

如何typeof(SqlException)在.NET CORE中使用?

Tân*_*Tân 8

在.Net Core版本中,使用前需要安装此包:Microsoft.EntityFrameworkCore.SqlServer

安装包 Microsoft.EntityFrameworkCore.SqlServer -版本 2.1.4

try
{
    // code goes here...    
}
catch (SqlException sqlEx)
{
    // code goes here...
}
catch (Exception ex)
{
    // other exception...
}
Run Code Online (Sandbox Code Playgroud)

  • 要在同一块中捕获“SqlException”或“SqliteException”,可以使用“DbException”,因为它是 _Sql_ 和 _Sqlite_ 提供程序以及毫无疑问的未来提供程序的基础。 (2认同)