Execute Stored Procedures In MVC Core Using Entity Framework Core

Entity Framework Core allows us to execute Stored Procedures from .NET Core applications. Entity Framework Core provides the following two methods to execute Stored Procedures.

  1. FromSql() Method
  2. ExecuteSqlCommand() Method

The first method, FromSql() is used to execute a Stored Procedure that retrieves records from database tables and the second method, ExecuteSqlCommand() is used to execute a Stored Procedure that inserts, updates, or deletes records from a database. The second method, ExecuteSqlCommand() executes a Stored Procedure and returns an integer value that indicates the number of rows affected. To execute a Stored Procedure from .NET Core web application using database first approach, we need to follow the following steps.

  1. Create a Stored Procedure
  2. Create MVC Core Web Application
  3. Create a Model of Stored Procedure
  4. Set Model of Stored Procedure in DbContext Class
  5. Execute Stored Procedure
  6. Create View

Create a Stored Procedure

To create a Stored Procedure, follow the following steps:

  • Open SQL Server Management Studio 2017, and in the Object Explorer pane expand databases folder and select the database name in which you want to create your Stored Procedure.
  • Now expand the programmability folder under your selected database name, then right click on the Stored Procedures folder. When you right click on the Stored Procedures folder, it will open a Query editor that contains a prototype for your Stored Procedure.
  • Now put your Stored Procedure Query and parameters if necessary and press the execute option from the main menu of SQL Server Management Studio. When you press the Execute option, your Stored Procedure will be created in the underlying database.

Suppose you have the following Stored Procedure,

  1. USE [EmployeesDB]  
  2. GO  
  3.   
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8.   
  9. CREATE PROCEDURE [dbo].[RetrieveEmployeeRecord]   
  10.       
  11.  @EmpCode nvarchar(50)  
  12.   
  13. AS  
  14. BEGIN  
  15.     SET NOCOUNT ON;  
  16.   
  17. SELECT EmpCode, EmpFullName, EmpGender, EmpBirthDate, EmpJoiningDate, EmpMobileNumber, EmpEmailAddress, EmpPicture, BranchName, DepartmentName  
  18. from EmployeeGeneralDetails e inner join Branches b on e.EmpBranchCode = b.BranchCode  
  19. inner join Departments d on e.EmpDepttCode = d.DepartmentID  
  20. where EmpCode = @EmpCode  
  21. END  

The name of the above Stored Procedure is RetrieveEmployeeRecord and it retrieves records from three tables that are EmployeeGeneralDetails, Branches and Departments using inner join Query.

Create MVC Core Web Application

To create an MVC Core web application, open Visual Studio.NET 2017 or later version, open New Project and select ASP.NET Core Web Application template, give a name to your MVC Core application project and press the OK button. Suppose the name of your MVC Core web application is ProcedureTest. When you created your MVC Core web application project, all the necessary files and folders are displayed in the Solution Explorer window located on the right side pane of the Visual Studio.

Create a Model of Stored Procedure

Now, create a model class that shows all the projected fields or columns of the Stored Procedure you want to execute. In model class, define properties for each projected column of the Stored Procedure. The projected columns or fields means the number of columns you want to retrieve from database tables.

When you create MVC Core web application, then from the Solution Explorer window, right click on the Models folder of your project, and create a new class. Now give name to your model class. You can give any name to your model class but usually it is same as the name of your Stored Procedure.
Since the name of our created Stored Procedure is RetrieveEmployeeRecord therefore, the model class name is also should be RetrieveEmployeeRecord. Following is the code of the model class for the above Stored Procedure,
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace ProcedureTest.Models  
  5. {  
  6.     public class RetrieveEmployeeRecord  
  7.     {   
  8.         [Key]  
  9.         public string EmpCode { getset; }  
  10.         public string EmpFullName { getset; }  
  11.         public string EmpGender { getset; }  
  12.         public DateTime? EmpBirthDate { getset; }  
  13.         public DateTime? EmpJoiningDate { getset; }  
  14.         public string EmpMobileNumber { getset; }  
  15.         public string EmpEmailAddress { getset; }  
  16.         public string EmpPicture { getset; }  
  17.         public string BranchName { getset; }  
  18.         public string DepartmentName { getset; }        
  19.     }  
  20. }  

The model class must be designed according to the query of the Stored Procedure. The projected fields or columns of the Stored Procedure must be the same as the properties of the model class. Each property of the model class is related with each field or column of the Stored Procedure.

Set Model of Stored Procedure in DbContext Class

After creating the model class, now open your data context class and add new DbSet with your created model class. The data context class is a class which is derived from the DbContext class. Following is the DbSet for the above model class:

  1. public virtual DbSet<RetrieveEmployeeRecord> RetrieveEmployeeRecord {getset;}  

Execute Stored Procedure

To execute a Stored Procedure the FromSql() method or ExecuteSqlCommand() method is used. Here we are using the FromSql() method because we are executing a Stored Procedure that retrieves record from database tables. To execute Stored Procedure using FromSql() method, open the HomeController of your project and put the following code in the Index action method,

  1. public IActionResult Index(string id) {  
  2.     var empRecord = dbContext.RetrieveEmployeeRecord.FromSql($ "RetrieveEmployeeRecord {id}").ToList();  
  3.     return View(empRecord);  
  4. }  

The name of the Stored Procedure is RetrieveEmployeeRecord and the name of the model class is also RetrieveEmployeeRecord. The dbContext.RetrieveEmployeeRecord indicates the model class. The FromSql() method takes the Stored Procedure name as argument that is FromSql($"RetrieveEmployeeRecord {id}"). The {id} indicates the parameter of the Stored Procedure. If you want to execute a Stored Procedure that does not take any parameter then use the FromSql method as FromSql($"RetrieveEmployeeRecord"). If your Stored Procedure takes more than one parameter then you can use multiple parameters in the FromSql() method separating by comma. Suppose your Stored Procedure takes two parameters then you can use the FromSql() method as bellow,

  1. FromSql($"RetrieveEmployeeRecord {param1}, {param2}")  

In the above FromSql() method, the {param1} indicates the first parameter of the Stored Procedure and {param2} indicates the second parameter of the Stored Procedure.

Create View

Now open the view file Index.cshtml and put the following code,

  1. @model IEnumerable< ProcedureTest.Models.RetrieveEmployeeRecord>  
  2. <style type="text/css">  
  3. @@media only screen and (min-width: 300px) {  
  4. table, th, td {  
  5.    border: 1px solid black;  
  6.    text-align: center;  
  7. }  
  8. th {  
  9.    height: 50px;  
  10.    background-color: darkgray;  
  11.    color: white;  
  12.    font-size: 14px;  
  13.    white-space:nowrap;  
  14. }  
  15. tr {  
  16.    height: 30px;  
  17. }  
  18. tr:nth-child(even) {  
  19.    background-color: #f2f4f5;  
  20. }  
  21. td {  
  22.    font-size: 12px;  
  23.    white-space: nowrap;  
  24. }  
  25. }  
  26. </style>  
  27. <div class="row">  
  28.     <div class="col-md-12">  
  29.         <table>  
  30.             <thead>  
  31.                 <tr>  
  32.                     <th>Code</th>  
  33.                     <th>Name</th>  
  34.                     <th>Gender</th>  
  35.                     <th>Birth Date</th>  
  36.                     <th>Joining Date</th>  
  37.                     <th>Mobile Number</th>  
  38.                     <th>Email</th>  
  39.                     <th>Branch</th>  
  40.                     <th>Department</th>  
  41.                     <th>Picture</th>  
  42.                 </tr>  
  43.             </thead>  
  44.             <tbody>  
  45. @foreach (var item in Model)  
  46. {  
  47.   
  48.                 <tr>  
  49.                     <td>@item.EmpCode</td>  
  50.                     <td>@item.EmpFullName</td>  
  51.                     <td>@item.EmpGender</td>  
  52.                     <td>@item.EmpBirthDate.Value.ToString("dd/MM/yyyy")</td>  
  53.                     <td>@item.EmpJoiningDate.Value.ToString("dd/MM/yyyy")</td>  
  54.                     <td>@item.EmpMobileNumber</td>  
  55.                     <td>@item.EmpEmailAddress</td>  
  56.                     <td>@item.BranchName</td>  
  57.                     <td>@item.DepartmentName</td>  
  58.                     <td>  
  59.                         <input type="image" src="~/Images/@item.EmpPicture" style="width:120px; height:80px;" />  
  60.                     </td>  
  61.                 </tr>  
  62. }  
  63.   
  64.             </tbody>  
  65.         </table>  
  66.     </div>  
  67. </div>  


Similar Articles