且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Database.SqlQuery调用具有多个输出参数的存储过程

更新时间:2023-09-13 14:53:10

您尝试使用的方法仅适用于查询结果,它无法自动将输出参数的值放入新对象中。

The method you are trying to use only works for results of a query. It can't put the values of the output parameters into a new object for you automatically.

必须在运行存储过程后显式创建参数并读取它们的值。

You have to create the parameters explicitly and read their values after the stored procedure has been run.

因此,如果您有这样的存储过程:

So if you have a stored procedure like this:

CREATE PROCEDURE dbo.insertemployee
(
    @iName varchar(500),
    @OEmployeeId int OUTPUT,  
    @OSalary Money OUTPUT
)
AS
BEGIN
    SELECT @OEmployeeId = 1337;
    SELECT @OSalary = 1000;
END

...您可以执行它并获取像这样的参数结果:

... you can execute it and get the results of the parameters like this:

using (var ctx = new Context())
{
    var nameParam = new SqlParameter("iName", "TestName");

    var employeeIdParam = new SqlParameter("OEmployeeId", SqlDbType.Int) 
    { 
        Direction = System.Data.ParameterDirection.Output 
    };

    var salaryParam = new SqlParameter("OSalary", SqlDbType.Money) 
    { 
        Direction = System.Data.ParameterDirection.Output 
    };

    ctx.Database.ExecuteSqlCommand(
        "insertemployee @iName, @OEmployeeId out, @OSalary out", 
        nameParam, employeeIdParam, salaryParam);

    var employeeId = (int)employeeIdParam.Value;
    var salary = (decimal)salaryParam.Value;
}