hesh
hesh

Reputation: 65

ASP.NET MVC4 return output from a stored procedure with Entity Framework

I been trying to get a simple output from a stored procedure

ALTER PROCEDURE [dbo].[sp_getrandomnumber]
        @randoms int output
AS
begin
  set @randoms =12345
end

and my mvc

    public ActionResult Index()
    {
        var qry = db.sp_getrandomnumber(ref randoms); 
      ......
     return View();
    }
}

but when I compile I get errors on the var qry section saying the following

No overload for method 'sp_getrandomnumber' takes 1 arguments

The name 'randoms' does not exist in the current context

I tried following this tutorial http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx

many thanks in advance Hesh

Upvotes: 0

Views: 3611

Answers (1)

Sam Leach
Sam Leach

Reputation: 12956

Your problem is that your SPROC output is an int.

See the following quote from Scott Gu's article.

"LINQ to SQL maps "out" parameters in SPROCs as reference parameters (ref keyword), and for value types declares the parameter as nullable."

So you need to make sure you're declaring randoms as a nullable int.

Change your sp call to

public ActionResult Index()
{   
    // @randoms int output from SPROC.
    int? randoms = null;

    // qry would contain a select if you had one in the SPROC.
    var qry = db.sp_getrandomnumber(ref randoms); 

    // randoms is 12345

    return View();
}

Find another example here.

Upvotes: 1

Related Questions