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

时间:2020-01-21 09:16:41

标签: c# .net .net-core .net-core-3.1

我想在Dot Net core 3.1中执行带有输出参数的存储过程。 我正在使用lead = Lead.objects.get(id=id) .... ..... if form.is_valid(): item = form.instance item.save() lead.ticket_set.add(item) lead.save() 类的<dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-clients_2.11</artifactId> <version>1.9.1</version> </dependency> 扩展方法。

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

ExecuteSqlInterpolated

执行后,employeeCount为DatabaseFacade,而string deptName="IT"; int? employeeCount = null; Database.ExecuteSqlInterpolated($"exec dbo.usp_GetEmpCountByDept {deptName}, {employeeCount} out"); 是返回值。 由于某些人要求存储用于重现该问题的proc代码,因此我将pr​​oc存储如下:

null

3 个答案:

答案 0 :(得分:3)

我找到了另一种对我有用的方法

  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;
     }

答案 1 :(得分:0)

ExecuteSqlInterpolated对数据库执行给定的SQL,并返回受影响的行数。

您不能期望通过此方法返回数据。

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

答案 2 :(得分:0)

更改此

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;