October 08, 2014

Context Database SqlQuery executes Stored Procedure and get Return Values

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 prodcudure like this:
CREATE PROCEDURE dbo.insertemployee
    @iName varchar(500),
    @OEmployeeId int OUTPUT,  
    @OSalary Money OUTPUT
    SELECT @OEmployeeId = 1337;
    SELECT @OSalary = 1000;
... 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 

        "insertemployee @iName, @OEmployeeId out, @OSalary out", 
        nameParam, employeeIdParam, salaryParam);

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

No comments: