Jac*_*han 13 linq-to-entities stored-procedures
这是我的SQL Server存储过程:
ALTER PROCEDURE [dbo].[SearchUser]
(@Text NVARCHAR(100),
@TotalRows INT = 0 OUTPUT)
AS
BEGIN
SELECT @TotalRows=1000
SELECT * from Users
END
Run Code Online (Sandbox Code Playgroud)
还有我的C#代码
using (var context = new TestDBEntities())
{
var outputParameter = new ObjectParameter("TotalRows", typeof(Int32));
context.SearchUser("", outputParameter);
Response.Write(outputParameter.Value);
}
Run Code Online (Sandbox Code Playgroud)
但outputParameter.Value总是为空.
谁能告诉我为什么?
Ser*_*kov 44
在执行存储过程期间,输出参数由其实际值填充.
但是,当您尝试迭代结果记录集但不调用包装器方法时,表值存储过程实际上只会执行.
所以,这个DOES'T工作:
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);
}
Run Code Online (Sandbox Code Playgroud)
这样做:
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);
}
Run Code Online (Sandbox Code Playgroud)
当您使用存储过程时不返回任何记录集时,它们会在方法调用后立即执行,因此您在输出参数中具有实际值.