从存储过程获取返回值

我使用的是Code First方法的entity framework5。 我需要从存储过程读取返回值; 我已经阅读输出参数和发送input参数,但我不知道如何读取返回值。

可能吗?

这里是我用来调用存储过程的代码:

var outParam = new SqlParameter(); outParam.ParameterName = "@StatusLog"; outParam.SqlDbType = SqlDbType.NVarChar; outParam.Size = 4000; outParam.Direction = ParameterDirection.Output; var code = new SqlParameter(); code.ParameterName = "@Code"; code.Direction = ParameterDirection.Input; code.SqlDbType = SqlDbType.VarChar; code.Size = 20; code.Value = "123"; var data = _context.Database.SqlQuery<Item>("exec spItemData @Code, @StatusLog OUT", code, outParam); var result = data.FirstOrDefault(); 

我find了! 我可以读取返回值的输出参数,必须以这种方式使用:

 // define a new output parameter var returnCode = new SqlParameter(); returnCode.ParameterName = "@ReturnCode"; returnCode.SqlDbType = SqlDbType.Int; returnCode.Direction = ParameterDirection.Output; // assign the return code to the new output parameter and pass it to the sp var data = _context.Database.SqlQuery<Item>("exec @ReturnCode = spItemData @Code, @StatusLog OUT", returnCode, code, outParam); 

由Daniele提供的解决scheme并不适合我,直到我findDiego Vega的 博客文章 ,它解释说:

在访问输出参数(…)的值之前,您需要阅读整个结果。这就是存储过程的工作方式,而不是特定于此EFfunction的。

另外,在我的情况下,我没有返回一个实体,我只需要执行存储过程,所以我用_context.Database.SqlQuery<object> objectreplace了Item

这里是示例代码:

 var code = new SqlParameter("@Code", 1); var returnCode = new SqlParameter("@ReturnCode", SqlDbType.Int); returnCode.Direction = ParameterDirection.Output; var outParam = new SqlParameter("@StatusLog", SqlDbType.Int); outParam.Direction = ParameterDirection.Output; var sql = "exec @ReturnCode = spSomeRoutine @Code, @StatusLog OUT"; var data = _context.Database.SqlQuery<object>(sql, returnCode, code, outParam); // Read the results so that the output variables are accessible var item = data.FirstOrDefault(); var returnCodeValue = (int)returnCode.Value; var outParamValue = (int)outParam.Value; 

这是一个示例存储过程:

 CREATE PROCEDURE [dbo].[spSomeRoutine] @Code Int, @StatusLog INT OUTPUT AS BEGIN SET @StatusLog = 5 RETURN 10 END 

在存储过程没有输出参数的情况下,我做了以下操作,有效地使一些Sql返回一个select语句;

 var data = context.Database.SqlQuery<int>(@"declare @num int exec @num = myStoredProcThatReturnsInt select @num"); var result = data.First(); 

您可以将存储过程添加为EF函数,然后从上下文中直接调用它。

请参阅http://www.entityframeworktutorial.net/EntityFramework4.3/execute-stored-procedure-using-dbcontext.aspx

获取更多信息