How to call stored procedure in EF4
I'm trying to call a stored procedure in Entity Framework 4 application and so far getting strange results. Stored procedure takes IN
and OUT
parameters, and returns resultset. I mapped stored procedure and created a complex type that represents a row in returned resultset. I call it
using (MyObjectContext ctx = new MyObjectContext())
{
ObjectParameter out1 = new ObjectParameter("out1", typeof(String));
ObjectParameter out2 = new ObjectParameter("out2", typeof(String));
var res = ctx.my_proc(1,2, out1,out2);
}
The problem is that unless I call res.ToList()
(or enumerate through res
, or 开发者_高级运维call any methods that accesses underlying collection), values of out1
and out2
are null
.
You cannot fix it. It is a gotcha. Result set must be materialized or thrown away before output parameters are accessible because these output parameters are transferred in the last result set so internal data reader must first read the returning result set with main data and then access the next result set to read output parameters. Btw. it is the same if you use ADO.NET directly - that is not a feature of Entity framework itself but the way how SQL server returns output parameters and the way how DataReader consumes result sets in sequential order.
when u call procedure or query that returns a table of rows EF does real execution when user calls ToList or enumerate the return value
精彩评论