Call Stored Procedure From Entity Framework


In this article, I will demonstrate how to call a Stored Procedure from Entity Framework. There are many ways to call Stored Procedures from Entity Framework.


The prerequisite for running these examples are the following sample tables with test data and a Stored Procedure. The following script help to generate the table with test data and a Stored Procedure.

  1. --First we create Department Master and Employee Master tables.  
  2. IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DepartmentMaster]'AND type in (N'U'))  
  3. DROP TABLE [dbo].[DepartmentMaster]  
  4. GO  
  5. CREATE TABLE [dbo].[DepartmentMaster](  
  6.                [DepartmentId] [int] IDENTITY(1,1) NOT NULL,  
  7.                [DepartmentName] [varchar](50) NULL,  
  8.                [Status] [tinyint] NULL,  
  10. (  
  11.                [DepartmentId] ASC  
  13. ON [PRIMARY]  
  15. IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmployeeMaster]'AND type in (N'U'))  
  16. DROP TABLE [dbo].[EmployeeMaster]  
  17. GO  
  19. CREATE TABLE [dbo].[EmployeeMaster](  
  20.                [EmployeeID] [int] IDENTITY(1,1) NOT NULL,  
  21.                [EmployeeName] [varchar](100) NULL,  
  22.                [DepartmentID] [intNULL,  
  23.                [Status] [tinyint] NULL,  
  25. (  
  26.                [EmployeeID] ASC  
  28. ON [PRIMARY]  
  30. --Stored Procedure that return Employee Details i.e Employee ID, Employee Name and Department Name  
  32. IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetEmployeeData]'AND type in (N'P', N'PC'))  
  33. DROP PROCEDURE [dbo].[GetEmployeeData]  
  34. GO  
  35. CREATE PROCEDURE [dbo].[GetEmployeeData]  
  36. AS  
  37. BEGIN  
  38.                SELECT EmployeeID,EmployeeName,DepartmentName FROM EmployeeMaster E   
  39.                               INNER JOIN DepartmentMaster D ON E.DepartmentID = D.DepartmentId  
  40. END  
  42. --Inserting some Dummy Data.  
  44. SET IDENTITY_INSERT [dbo].[DepartmentMaster] ON  
  45. INSERT [dbo].[DepartmentMaster] ([DepartmentId], [DepartmentName], [Status]) VALUES (1, N'Maths', 0)  
  46. INSERT [dbo].[DepartmentMaster] ([DepartmentId], [DepartmentName], [Status]) VALUES (2, N'English', 0)  
  47. INSERT [dbo].[DepartmentMaster] ([DepartmentId], [DepartmentName], [Status]) VALUES (3, N'Physics', 0)  
  48. SET IDENTITY_INSERT [dbo].[DepartmentMaster] OFF  
  50. SET IDENTITY_INSERT [dbo].[EmployeeMaster] ON  
  51. INSERT [dbo].[EmployeeMaster] ([EmployeeID], [EmployeeName], [DepartmentID], [Status]) VALUES (1, N'Tejas', 1, 0)  
  52. INSERT [dbo].[EmployeeMaster] ([EmployeeID], [EmployeeName], [DepartmentID], [Status]) VALUES (2, N'Rakesh', 1, 0)  
  53. INSERT [dbo].[EmployeeMaster] ([EmployeeID], [EmployeeName], [DepartmentID], [Status]) VALUES (3, N'Jignesh', 2, 0)  
  54. INSERT [dbo].[EmployeeMaster] ([EmployeeID], [EmployeeName], [DepartmentID], [Status]) VALUES (4, N'Kunal', 3, 0)  
  55. SET IDENTITY_INSERT [dbo].[EmployeeMaster] OFF  

1. Stored Procedure as Entity Function

The Entity Framework has the capability of importing a Stored Procedure as a function. We can also map the result of the function back to any entity type or complex type.

The following is the procedure to import and use a Stored Procedure in Entity Framework.

Step 1: Import Stored Procedure


When we finish this process, the selected Stored Procedure is added to the model browser under the Stored Procedure Node.

Step 2: Right-click Stored Procedure and select "Add Function Import".


Step 3: Here, we can map a returned object of our Stored Procedure. The return type may be a scalar value or a collection of Model Entities or a collection of Complex (Custom) Entity. From this screen we can create a Complex Entity as well.



Now, we can call the Stored Procedure as an entity function using the following code. The entity function returns a complex type called "EmployeeDetails".

  1. using (Entities context = new Entities())  
  2. {  
  3.     IEnumerable<EmployeeDetails> empDetails = context.GetEmployeeData();  
  4. }  
2. Call Stored Procedure using ExecuteStoreQuery<T> function

"ExecuteStoreQuery<T>" should be used to query data. This method only works if T has a Default Constructor and also a Property name is the same as the returned column names. "T" can be any generic class or any data type and it might not be a part of an EF generated entity.

The following is the procedure to retrieve data using the "ExecuteStoreQuery<T>" method from a Stored Procedure.

Step 1:

The method "T" can be anything, it may be an EF Generated entity or it may be a Custom Entity, so first I am creating a Custom Entity "EmployeeDetail". Here the EmployeeDetail properties name must be the same as the returned column of the select statement of the Stored Procedure.


  1. // Creating Custom class to hold result of Stored Procedure  
  2. public class EmployeeDetail  
  3. {  
  4.     public int EmployeeID { get; set; }  
  5.     public string EmployeeName { get; set; }  
  6.     public string DepartmentName { get; set; }  
  7. }  
  9. // using Object Context (EF4.0)  
  10. using (Entities context = new Entities())  
  11. {  
  12.         IEnumerable<EmployeeDetails> empDetails  =  context.ExecuteStoreQuery<EmployeeDetails>      
  13.                                                                                             ("exec GetEmployeeData").ToList();  
  14. }  
  16. // using DBContext (EF 4.1 and above)  
  17. using (Entities context = new Entities())  
  18. {  
  19.         IEnumerable<EmployeeDetails> empDetails  =  context. Database.SqlQuery  
  20.                                                                       < EmployeeDetails >("exec GetEmployeeData "null).ToList();  
  21. }  

3. Call Stored Procedure using DbDataReader

We can also retrieve data or call a Stored Procedure using a SQL Connection Command and DbDataReader. The Object Context has a translate method that translates the entity data from DbDataReader into the requested type object. This method enables us to execute a standard ADO.Net query against a data source and return data rows into entity objects. Using the following code we can call a Stored Procedure and retrieve data in entity form.

  1. using (Entities context = new Entities())  
  2. {  
  3.   string ConnectionString = (context.Connection as EntityConnection).StoreConnection.ConnectionString;  
  4.     SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);  
  5.     builder.ConnectTimeout = 2500;  
  6.     SqlConnection con = new SqlConnection(builder.ConnectionString);  
  7.     System.Data.Common.DbDataReader sqlReader;  
  8.     con.Open();  
  9.     using (SqlCommand cmd = con.CreateCommand())  
  10.     {  
  11.         cmd.CommandText = "GetEmployeeData";  
  12.         cmd.CommandType = System.Data.CommandType.StoredProcedure;  
  13.         cmd.CommandTimeout = 0;  
  15.       sqlReader = (System.Data.Common.DbDataReader)cmd.ExecuteReader();  
  16.       IEnumerable<EmployeeDetail> empDetails = context.Translate<EmployeeDetail>(sqlReader).ToList();  
  17.     }  
  18. }  


Using the methods described above, we can call a Stored Procedure and retrieve data as a scalar or complex value.

Up Next
    Ebook Download
    View all
    View all