实体框架使用函数导入时无法获取输出参数 [英] I cannot get the output parameter when use function import by Entity Framework
本文介绍了实体框架使用函数导入时无法获取输出参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的 SQL Server 存储过程:
Here's my SQL Server stored procedure :
ALTER PROCEDURE [dbo].[SearchUser]
(@Text NVARCHAR(100),
@TotalRows INT = 0 OUTPUT)
AS
BEGIN
SELECT @TotalRows=1000
SELECT * from Users
END
还有我的 C# 代码
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
context.SearchUser("", outputParameter);
Response.Write(outputParameter.Value);
}
但是outputParameter.Value
总是为空.
谁能告诉我为什么?
推荐答案
在存储过程执行期间输出参数由其实际值填充.
Output parameters filled by its actual values during the execution of the stored procedure.
但是表值存储过程实际上仅在您尝试迭代结果记录集但不调用包装方法时才会执行.
But table-valued stored procedure actually get executed only in moment when you're trying to iterate resulting recordset, but not calling a wrapper method.
所以,这行不通:
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
context.SearchUser("", outputParameter);
// Paremeter value is null, because the stored procedure haven't been executed
Response.Write(outputParameter.Value);
}
这样做:
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
// Procedure does not executes here, we just receive a reference to the output parameter
var results = context.SearchUser("", outputParameter);
// Forcing procedure execution
results.ToList();
// Parameter has it's actual value
Response.Write(outputParameter.Value);
}
当您使用不返回任何记录集的存储过程时,它们会在方法调用后立即执行,因此您在输出参数中有实际值.
When you're working with stored procedures what don't return any recordset, they execute immediately after a method call, so you have actual value in output parameter.
这篇关于实体框架使用函数导入时无法获取输出参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文