First, in EF4.1, create a stored procedure with an output parameter.

ef-code-first entity-framework parameters stored-procedures

Question

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?

1
11
11/18/2011 9:31:21 AM

Accepted Answer

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;
26
11/18/2011 12:42:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow