I would like to execute a stored procedure with output parameter in Dot Net core 3.1.
I am using the ExecuteSqlInterpolated
extension method of a DatabaseFacade
class.
C# code to get employee's count.
string deptName="IT";
int? employeeCount = null;
Database.ExecuteSqlInterpolated($"exec dbo.usp_GetEmpCountByDept {deptName}, {employeeCount} out");
After execution employeeCount is null
and -1
is the return value.
As some people requested stored proc code for reproducing the issue ,I have stored proc as below
CREATE PROCEDURE usp_GetEmpCountByDept
@Dept nvarchar(20),
@EmpCount int Output
AS
BEGIN
SELECT @EmpCount = COUNT(Id)
FROM [dbo].[Employees]
WHERE Department = @Dept
END
I have found other way which is working for me
Add Nuget package Microsoft.Data.SqlClient
Use ExecuteSqlRaw method instead
Below is the code
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;
}
change this
string deptName="IT";
int? employeeCount = null;
Database.ExecuteSqlInterpolated($"exec dbo.usp_GetEmpCountByDept {deptName}, {employeeCount} out");
to this (worked for me with .NET 5, don't know about earlier)
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With