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

Vis*_*l P 6 .net c# .net-core .net-core-3.1

我想在 Dot Net core 3.1 中执行一个带有输出参数的存储过程。我正在使用类的ExecuteSqlInterpolated扩展方法DatabaseFacade

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

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

执行后employeeCount 是null-1是返回值。由于有些人要求存储 proc 代码来重现该问题,因此我将 proc 存储如下

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

Vis*_*l P 5

我找到了其他对我有用的方法

  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;
     }
Run Code Online (Sandbox Code Playgroud)


r3m*_*ark 5

改变这个

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

对此(在.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;
Run Code Online (Sandbox Code Playgroud)