Monojit Sarkar Monojit Sarkar - 4 months ago 21
C# Question

How to retrieve output parameter from stored procedure by EF code first

i am new in EF and working with EF code first. just got a link which show how to use read output type param by EF db first. so anyone tell me how to retrieve output parameter from stored procedure by EF code first ?

if possible give me small sample code or redirect me to relevant articles.


I got a solution

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),
var result = data.ToList();
totalRows = (int)outParam.Value;


To retrieve the data for a stored procedure call, you can use the following

using(var db = new YourConext())
       var details = db.Database.SqlQuery<YourType>("exec YourProc @p", 
                      new SqlParameter("@p", YourValue));

YourType: might be int or string or long or even a ComplexType

@p: in case if the stored procedure has parameters and you can define as many as you need from parameters

if you need more information about SqlQuery , you might check the following

  1. Writing SQL queries for entities
  2. Entity Framework Code First and Stored Procedures

Hope this will help you