Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF4.1 Code First: Stored Procedure with output parameter

I use Entity Framework 4.1 Code First. I want to call a stored procedure that has an output parameter and retrieve the value of that output parameter in addition to the strongly typed result set. Its a search function with a signature like this

public IEnumerable<MyType> Search(int maxRows, out int totalRows, string searchTerm) { ... }

I found lots of hints to "Function Imports" but that is not compatible with Code First. I can call stored procedures using Database.SqlQuery(...) but that does not work with output parameters.

Can I solve that problem using EF4.1 Code First at all?

like image 435
Sebastian Weber Avatar asked Nov 18 '11 09:11

Sebastian Weber


1 Answers

SqlQuery works with output parameters but you must correctly define SQL query and setup SqlParameters. Try something like:

var outParam = new SqlParameter();
outParam.ParameterName = "TotalRows";
outParam.SqlDbType = SqlDbType.Int;
outParam.ParameterDirection = ParameterDirection.Output;

var data = dbContext.Database.SqlQuery<MyType>("sp_search @SearchTerm, @MaxRows, @TotalRows OUT", 
               new SqlParameter("SearchTerm", searchTerm), 
               new SqlParameter("MaxRows", maxRows),
               outParam);
var result = data.ToList();
totalRows = (int)outParam.Value;
like image 111
Ladislav Mrnka Avatar answered Oct 17 '22 17:10

Ladislav Mrnka