简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM