Introduction
Executing Stored Procedure that accepts parameters and returns resultset using Entity Framework DataContext with code first or database first approach.
Background
Most of the times, we need to execute stored procedures than get the result set even though we decide to use entity framework. It's pretty straight forward to leverage ADO.NET and DataSet
to retrieve the result returned from the Stored Procedure. It's not that common to do this using Entity Framework DataContext
.
Using the Code
Below are the steps and key points:
var param1 = new SqlParameter { ParameterName = "@paramName1",
SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input, Value = 1 };
var param2 = new SqlParameter { ParameterName = "@paramName2",
SqlDbType = SqlDbType.VarChar, Direction = ParameterDirection.Input, Value = "Test Input" };
var param3 = new SqlParameter { ParameterName = "@paramName3",
SqlDbType = SqlDbType.VarChar, Direction = ParameterDirection.Output, Size = 255 };
var SQLString = "EXEC [dbo].[name of the Stored Proc] @paramName1, @paramName2, @paramName3";
var employees= DataContext.Employee.SqlQuery(SQLString, param1, param2, param3);
(SQLString, param1, param2, param3)
Points of Interest
- In the above sample,
DataContext
would be the name of your DataContext
Instance variable - Employee would be name entity (POCO class) mapping to your database
- If the
resultset
returned by the SP would be mapped to the IEnumerable
collection of Entity - The above sample would return IEnumerable<Employee>
- We can use
<DataContext>.DataBase.SqlQuery
method or <DataContext>.<EntityName>.SqlQuery
- Your
out
param declared would have value returned by SP - The connect sting should have
MARS = true - MultipleActiveResultSets=true
Hands on Architect with 15 + years of experience in Microsoft technologies and worked for various clients across the globe. Has Insightful experience in Architecture, Design and Development of projects based on Microsoft Technologies. Worked with multiple fortune 500 customers. Possesses good knowledge on design patterns and best practices in .NET technologies.