如何在 Dot Net Core 3.1 中使用 FromSqlInterpolated/Database.ExecuteSqlInterpolated 执行带输出参数的存储过程?

How to execute stored procedure with Output parameters using FromSqlInterpolated/Database.ExecuteSqlInterpolated in Dot Net Core 3.1?

我想在 Dot Net core 3.1 中执行带输出参数的存储过程。 我正在使用 DatabaseFacade class.

ExecuteSqlInterpolated 扩展方法

获取员工人数的 C# 代码。

string deptName="IT";
int? employeeCount = null;
Database.ExecuteSqlInterpolated($"exec dbo.usp_GetEmpCountByDept {deptName}, {employeeCount} out");

执行后,employeeCount 为 null-1 为 return 值。 由于有些人要求存储过程代码以重现问题,我将过程存储如下

CREATE PROCEDURE usp_GetEmpCountByDept
@Dept nvarchar(20),
@EmpCount int Output
AS
BEGIN
SELECT @EmpCount = COUNT(Id)
FROM [dbo].[Employees] 
WHERE Department = @Dept
END

ExecuteSqlInterpolated 对数据库执行给定的 SQL 和 returns 受影响的行数。

您不能期望使用此方法返回数据。

请参阅此 MSDN 文档。 https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.relationaldatabasefacadeextensions.executesqlinterpolated?view=efcore-3.1

我找到了其他适合我的方法

  1. 添加 Nuget 包Microsoft.Data.SqlClient

  2. 改用 ExecuteSqlRaw 方法

下面是代码

    int? employeeCount = null;
    string deptName="IT";

    // Use Microsoft.Data.SqlClient namespace for SqlParameter.Visual studio will suggest  "system.data.sqlclient" which does not work
    var deptNameSQLParam = new Microsoft.Data.SqlClient.SqlParameter("@Dept", deptName);
    var employeeCountSQLParam = new Microsoft.Data.SqlClient.SqlParameter("@EmpCount", SqlDbType.Int) { Direction = ParameterDirection.Output }; 
    Database.ExecuteSqlRaw("exec dbo.usp_GetEmpCountByDept @Dept={0}, @EmpCount={1} out", deptNameSQLParam, employeeCountSQLParam);

     if (employeeCountSQLParam.Value != DBNull.Value)
     {
        employeeCount = (int)employeeCountSQLParam.Value;
     }

改变这个

string deptName="IT";
int? employeeCount = null;
Database.ExecuteSqlInterpolated($"exec dbo.usp_GetEmpCountByDept {deptName}, {employeeCount} out");

对此(我用 .NET 5 工作,之前不知道)

string deptName="IT";

// make explicit SQL Parameter
var output = new SqlParameter("@EmployeeCount", SqlDbType.Int) { Direction = ParameterDirection.Output };

// use output parameter instead
Database.ExecuteSqlInterpolated($"exec dbo.usp_GetEmpCountByDept {deptName}, {output} out");

// assign output
int? employeeCount = output.Value;