Entity Framework 6.0.0 Using Stored Procedure In ASP.NET MVC

Introduction

Entity Framework is an Object Relational Mapping (ORM) framework. ORM framework automatically makes classes based on database tables, and makes database tables based on classes. That is, it can also automatically generate necessary SQL to create database tables based on classes.

Patterns In Entity Framework

Data providers are source specific providers which abstract the ADO.NET interfaces to connect to the database when programming against the conceptual schema. It translates the common SQL languages such as LINQ via command tree to native SQL expression and executes it against the specific DBMS system. Entity Client layer exposes the entity layer to the upper layer. Entity client provides the ability for developers to work against entities in the form of rows and columns using Entity SQL queries without the need to generate classes to represent conceptual schema. Entity Client shows the entity framework layers which are the core functionality. These layers are called as Entity Data Model.

The Storage Layer contains the entire database schema in XML format.

The Entity Layer which is also an XML file defines the entities and relationships.

The Mapping layer is an XML file that maps the entities and relationships defined at conceptual layer with actual relationships and tables defined at logical layer.

The Metadata services which are also represented in Entity Client provide centralized API to access metadata stored Entity Mapping and Storage layers.

Object Services layer is the Object Context that represents the session of interaction between the applications and the data source. The main use of the Object Context is to perform different operations like add, delete instances of entities and to save the changed state back to the database with the help of queries. It is the ORM layer of Entity Framework that represents the data result to the object instances of entities. This service allows developers to use some of the rich ORM features like primary key mapping, change tracking, etc. by writing queries using LINQ and Entity SQL.

Entity Framework has the following three approaches,

  1. Schema First Approach
  2. Model First Approach
  3. Code First Approach

Schema First Approach

It can automatically generate necessary SQL to create database tables based on classes. Entity Framework can do all of the above automatically, if we provide it with the database schema.

The Database First Approach provides an alternative to the Code First and Model First approaches to the Entity Data Model.

It creates model codes like classes, properties, DbContext etc. from the database in the project and those classes become the link between the database and controller. The Database First approach creates the EF from an existing database. We use all the other functionalities, such as the model/database sync and the code generation, in the same way we used them in the Model First approach.

Model First Approach

In the Model First Approach, we first create the Entity Model.

  1. Entities
  2. Relationships between entities
  3. Inheritance hierarchies etc.

We implement all this directly on the design surface of the EDMX file.

The model is stored in an EDMX file and can be viewed and edited in the Entity Framework Designer. In Model First, you define your model in an Entity Framework designer then generate SQL, which will create database schema to match your model and then you execute the SQL to create the schema in your database. The classes that you interact with in your application are automatically generated from the EDMX file.

Code First Approach

Code-first approach allows us to create the custom classes first and based on these custom classes entity framework can generate database automatically for us successfully. Code First adds a model builder that inspects your classes that the context is managing, and then uses a set of rules or conventions to determine how those classes and the relationships describe a model, and how that model should map to your database. Code First has the ability to use that model to create a database if required. It can also update the database if the model changes, using a feature called Code First Migrations.

What is a EDMX

An .edmx file is an XML file that defines a conceptual model, a storage model, and the mapping between these models. An .edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically.

Transaction

Whenever you run SaveChanges() to insert, update or delete the database, the framework will put that operation in a transaction. When you invoke SaveChanges, the context automatically starts a transaction and commits or rolls it back. Starting a transaction requires that the store connection is open. So calling "Database.BeginTransaction()" will open the connection if it is not already opened. If DbContextTransaction opened the connection, then it will close it when Dispose() is called.

Types of Entity Framework

In Entity Framework, there are two types of entities that use their own custom data classes together with data model without making any modifications to the data classes themselves.

  • POCO entities
  • Dynamic Proxy
POCO Entities
  • POCO stands for "plain-old" CLR objects. POCO data classes which are mapped to entities are defined in a data model.
  • It also supports most of the same query, insert, update, and delete behaviors as entity types that are generated by the Entity Data Model tools.
Dynamic Proxy

While creating instances of POCO entity types , the Entity Framework often creates instances of a dynamically generated derived type that acts as a proxy for the entity. IT can also be said that it is a runtime proxy classes.
  • You can override some properties of the entity for performing actions automatically when the property is accessed.
  • This technique used to those models which are created with Code First and EF Designer.
Relationships In Entity Framework

There are three types of Relationships,
  • One-to-Many Relationship
  • Many-to-Many Relationship
  • One-to-One Relationship

One-to-Many Relationship

A one-to-many relationship is the most common type of relationship. In this type of relationship, a row in table X can have many matching rows in table Y, but a row in table Y can have only one matching row in table X. The foreign key is defined in the table that represents the many ends of the relationship.

Many-to-Many Relationship

In many-to-many relationship, a row in table X can have many matching rows in table Y, and vice versa. You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table X and table Y.

One-to-One Relationship

In a one-to-one relationship, a row in table X can have no more than one matching row in table Y, and vice versa. A one-to-one relationship is created if both of the related columns are primary keys or have unique constraints. In a one-to-one relationship, the primary key acts additionally as a foreign key and there is no separate foreign key column for either table.

DbContext In Entity Framework

Multiple DbContext was first revealed in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases.

Steps to create a simple application

Step 1

First create an MVC application named “MvcApplication2”.

ASP.NET
Step 2

Then, create one table named “tblCustomers”.

Script for tblCustomers 

  1. CREATE TABLE [dbo].[tblCustomers](  
  2.     [ID] [intNOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [City] [nvarchar](50) NULL,  
  5.     [Country] [nvarchar](50) NULL,  
  6.  CONSTRAINT [PK_tblCustomers] PRIMARY KEY CLUSTERED   
  7. (  
  8.     [ID] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]  
  11. GO   

Enter some dummy records into this table.

ASP.NET

Step 3

Then, create one stored procedure named “Sp_SearchCustomers”.

Script for Sp_SearchCustomers 

  1. CREATE PROCEDURE Sp_SearchCustomers  
  2. @City NVARCHAR(70)  
  3. AS  
  4. BEGIN  
  5.       SET NOCOUNT ON;  
  6.       SELECT * FROM tblCustomers  
  7.       WHERE City LIKE '%' + @City + '%'  
  8. END   

Here, I filtered the records based on City Column values.

Now, execute this stored procedure to filter records based on City Column values. 

  1. exec Sp_SearchCustomers 'Bangalore'  
  2. exec Sp_SearchCustomers 'Bhubaneswar'  

ASP.NET

Step 4

Follow these steps to create Entity Data Model.

So, create an ADO.NET Entity Data Model named “satyamodel.edmx”.

ASP.NET

Then

ASP.NET

Then, create a new connection using your SQL Server name and credentials using database name. You should select database where you created earlier created table and sp.

ASP.NET

Now, select this table name as mentioned above.

ASP.NET

You should now have the Entity Data Model ready with the tblCustomers Table.

ASP.NET

Once the Entity Framework is configured, the next step is to import the Stored Procedure in the Entity Framework model. In order to do so, you will need to Right Click the Entity Model and select Update Model from Database option as shown below.

ASP.NET

The above step will open the Update Wizard where you will need to select the above mentioned Stored Procedure and click Finish.

ASP.NET

Now we will need to import the Stored Procedure into the Entity Framework so that it can be called as a Function using Entity Framework. Thus you will need to Right Click the Entity Model, click Add and then click Function Import.

ASP.NET

This will open the Add Function Import dialog window. Here first you need to specify the Function Import Name which is the name of the function used to call the Stored Procedure and then select the Stored Procedure that will be executed when the function is called. The Return Type is selected as Entities which is the Customer Entity class.

Here the function import name is “SearchCustomers” and select your appropriate sp name in stored procedure/function name section. In Returns a collection of section , select your appropriate table name in entities selection option.

Click on Get column Information button in stored procedure/function column information section , It will show all related columns biodata as used in table and stored procedure.

ASP.NET

After completed all above steps successfully , You can see the structure of “satyamodel.edmx” in your application as all code and related class file auto generate by system regarding connection properties and entities of Table and Stored procedure.

ASP.NET

Also you can see the changes of some entity framework configuration related information made in “Web.Config” file.

ASP.NET

Step5

In “packages.config” , Check your Entity Framework Version Information.

ASP.NET

Step6

Create a controller class file named “HomeController.cs”.

Code Ref 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MvcApplication2.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         public ActionResult Index()  
  12.         {  
  13.             SatyaEntities entities = new SatyaEntities();  
  14.             return View(entities.SearchCustomers(""));  
  15.         }  
  16.   
  17.         [HttpPost]  
  18.         public ActionResult Index(string City)  
  19.         {  
  20.   
  21.             //if (Request.Form["text"] == null)  
  22.             //{  
  23.             //    TempData["SelectOption"] = -1;  
  24.             //}             
  25.             SatyaEntities entities = new SatyaEntities();  
  26.             return View(entities.SearchCustomers(City));  
  27.         }  
  28.           
  29.     }  
  30. }   

Code Description

The Controller consists of two Action methods.

Action method for manage GET operation.

Inside the Index Action method, the Stored Procedure is called using the SearchCustomers function created using the Function Import procedure done earlier.

The parameter City is passed as empty string and hence it gets all records from the tblCustomers table.

Finally the list of Customers Entity is returned to the View. 

  1. public ActionResult Index()  
  2.   {  
  3.       SatyaEntities entities = new SatyaEntities();  
  4.       return View(entities.SearchCustomers(""));  
  5.   }   

Action method for manage POST operation.

When the Form is submitted, the value of the City Name TextBox is submitted this Action method and the value is passed as parameter to the SearchCustomers function and the list of tblCustomers Entity is returned to the View. 

  1. [HttpPost]  
  2. public ActionResult Index(string City)  
  3. {  
  4.   
  5.     //if (Request.Form["text"] == null)  
  6.     //{  
  7.     //    TempData["SelectOption"] = -1;  
  8.     //}             
  9.     SatyaEntities entities = new SatyaEntities();  
  10.     return View(entities.SearchCustomers(City));  
  11. }   

Here I added some commented code for City name textbox validation if it was empty. 

  1. //if (Request.Form["text"] == null)  
  2.    //{  
  3.    //    TempData["SelectOption"] = -1;  
  4.    //}    

Here textbox type is “text” as mentioned in view.

  1. if (Request.Form["text"] == null)   

Here “SatyaEntities” the name of the entity when creation of “Ado.net entity data model” i.e. “satyamodel.edmx”

ASP.NET

Step7

Create a view file named “Index.cshtml”.

Code Ref 

  1. @model IEnumerable<MvcApplication2.tblCustomer>  
  2.   
  3. @{  
  4.     Layout = null;  
  5. }  
  6.   
  7. <!DOCTYPE html>  
  8.   
  9. <html>  
  10. <head>  
  11.     <meta name="viewport" content="width=device-width" />  
  12.     <title>Index</title>  
  13.     <style>  
  14.         table {  
  15.             font-family: arial, sans-serif;  
  16.             border-collapse: collapse;  
  17.             width: 100%;  
  18.         }  
  19.   
  20.         td, th {  
  21.             border: 1px solid #dddddd;  
  22.             text-align: left;  
  23.             padding: 8px;  
  24.         }  
  25.   
  26.         tr:nth-child(even) {  
  27.             background-color: #dddddd;  
  28.         }  
  29.   
  30.         .button {  
  31.             background-color: #4CAF50;  
  32.             border: none;  
  33.             color: white;  
  34.             padding: 15px 32px;  
  35.             text-align: center;  
  36.             text-decoration: none;  
  37.             display: inline-block;  
  38.             font-size: 16px;  
  39.             margin: 4px 2px;  
  40.             cursor: pointer;  
  41.         }  
  42.   
  43.         .button4 {  
  44.             border-radius: 9px;  
  45.         }  
  46.   
  47.         input[type=text], select {  
  48.             width: 60%;  
  49.             padding: 12px 20px;  
  50.             margin: 8px 0;  
  51.             display: inline-block;  
  52.             border: 1px solid #ccc;  
  53.             border-radius: 4px;  
  54.             box-sizing: border-box;  
  55.         }  
  56.     </style>  
  57.     </head>  
  58.     <body>  
  59.         <strong style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYA'S ENTITY FRAMEWORK SEARCH BY CITY</strong>  
  60.         <fieldset>  
  61.             <legend style="font-family:Arial Black;color:blue">SEARCH BY INDIAN METRO CITY</legend>  
  62.             @using (Html.BeginForm("Index""Home", FormMethod.Post))  
  63.         {  
  64.             <div align="center">  
  65.                     @Html.TextBox("City"""new { placeholder = "Enter Your City Here...." })  
  66.                     <input type="submit" class="button button4" value="Search" />  
  67.                 </div>  
  68.             <br />  
  69.             <br />  
  70.             <table align="center" border="1" cellpadding="4" cellspacing="4">  
  71.                     <tr>  
  72.                         <th style="background-color: Yellow;color: blue">Customer ID</th>  
  73.                         <th style="background-color: Yellow;color: blue">Customer Name</th>  
  74.                         <th style="background-color: Yellow;color: blue">City</th>  
  75.                         <th style="background-color: Yellow;color: blue">Country</th>  
  76.                     </tr>  
  77.                     @foreach (MvcApplication2.tblCustomer customer in Model)  
  78.                 {  
  79.                     <tr>  
  80.                             <td>@customer.ID</td>  
  81.                             <td>@customer.Name</td>  
  82.                             <td>@customer.City</td>  
  83.                             <td>@customer.Country</td>  
  84.                         </tr>  
  85.                 }  
  86.                 </table>  
  87.         }  
  88.             </fieldset>  
  89.   
  90.               @*@if (TempData["SelectOption"] != null)  
  91.               {  
  92.                 <script type="text/javascript">  
  93.                         alert("Enter Only One City To Filter Records");  
  94.                 </script>  
  95.               }*@    
  96.           
  97.             <footer>  
  98.                 <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  99.             </footer>  
  100. </body>  
  101.   
  102. </html>   

Code Description

Inside the View, in the first line the tblCustomer Entity is declared as IEnumerable which specifies that it will be available as a Collection.

  1. @model IEnumerable<MvcApplication2.tblCustomer>   

The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.

  1. @using (Html.BeginForm("Index""Home", FormMethod.Post))   

ActionName – Name of the Action. In this case the name is Index.

ControllerName – Name of the Controller. In this case the name is Home.

FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.

Inside the View, a TextBox is created using the Html.TextBox HTML Helper function and there is a Submit button which when clicked, the Form gets submitted. 

  1. <div align="center">  
  2.              @Html.TextBox("City"""new { placeholder = "Enter Your City Here...." })  
  3.              <input type="submit" class="button button4" value="Search" />  
  4. </div>   

For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the tblCustomer records.

  1. @foreach (MvcApplication2.tblCustomer customer in Model)   

Here I have applied some css style sheet for design Table whole. 

  1. table {  
  2.           font-family: arial, sans-serif;  
  3.           border-collapse: collapse;  
  4.           width: 100%;  
  5.       }  
  6.   
  7.       td, th {  
  8.           border: 1px solid #dddddd;  
  9.           text-align: left;  
  10.           padding: 8px;  
  11.       }  
  12.   
  13.       tr:nth-child(even) {  
  14.           background-color: #dddddd;  
  15.       }   

Here I have applied some css style sheet for design Button whole. 

  1. .button {  
  2.             background-color: #4CAF50;  
  3.             border: none;  
  4.             color: white;  
  5.             padding: 15px 32px;  
  6.             text-align: center;  
  7.             text-decoration: none;  
  8.             display: inline-block;  
  9.             font-size: 16px;  
  10.             margin: 4px 2px;  
  11.             cursor: pointer;  
  12.         }  
  13.   
  14.           
  15. .button4 {  
  16.             border-radius: 9px;  
  17.         }   

Here I have applied some css style sheet for design TextBox whole. 

  1. input[type=text], select {  
  2.             width: 60%;  
  3.             padding: 12px 20px;  
  4.             margin: 8px 0;  
  5.             display: inline-block;  
  6.             border: 1px solid #ccc;  
  7.             border-radius: 4px;  
  8.             box-sizing: border-box;  
  9.         }   

I added some placeholder in textbox.

  1. @Html.TextBox("City"""new { placeholder = "Enter Your City Here...." })   

Apply css in button control.

  1. <input type="submit" class="button button4" value="Search" />   

Mention some table header names. 

  1. <tr>  
  2.  <th style="background-color: Yellow;color: blue">Customer ID</th>  
  3.  <th style="background-color: Yellow;color: blue">Customer Name</th>  
  4.  <th style="background-color: Yellow;color: blue">City</th>  
  5.  <th style="background-color: Yellow;color: blue">Country</th>  
  6. </tr>   

I added one foreach loop will be executed over the Model which will generate the HTML Table rows with the tblCustomer records using variable customer.

Using variable customer we can access all entity property values. 

  1. @foreach (MvcApplication2.tblCustomer customer in Model)  
  2.                 {  
  3.                     <tr>  
  4.                             <td>@customer.ID</td>  
  5.                             <td>@customer.Name</td>  
  6.                             <td>@customer.City</td>  
  7.                             <td>@customer.Country</td>  
  8.                     </tr>  
  9.                 }   

I added here some commented code for validation if empty city name textbox. 

  1. @*@if (TempData["SelectOption"] != null)  
  2.               {  
  3.                 <script type="text/javascript">  
  4.                         alert("Enter Only One City To Filter Records");  
  5.                 </script>  
  6.               }*@   

This one related to controller class file related code. 

  1. //if (Request.Form["text"] == null)  
  2.             //{  
  3.             //    TempData["SelectOption"] = -1;  
  4.             //}     

As per your requirement you can uncomment and add.

ASP.NET

Step8

Set start page during first time load of your UI.

Code Ref 

  1. public static void RegisterRoutes(RouteCollection routes)  
  2.         {  
  3.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.   
  5.             routes.MapRoute(  
  6.                 name: "Default",  
  7.                 url: "{controller}/{action}/{id}",  
  8.                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  9.             )  
  10. }   

Code Description

Here name of the controller name is : “Home” .

Here name of the controller action method name is : “Index” .

ASP.NET

OUTPUT

The URL is : http://localhost:52827/Home/Index

Here, the name of the controller is : “Home” .

Here, the name of the controller action method is : “Index” .

ASP.NET

Here, I searched for Bhubaneswar City related records.

ASP.NET

Here, I searched for Bangalore City related records.

ASP.NET

Here, I searched for invalid City Name by putting USA.

ASP.NET

In footer section, it is showing Today’s Date Time.

ASP.NET

SUMMARY

In this article, we learned the following. 

  1. What Entity Framework is.
  2. Different parts of Entity Framework.
  3. How to create Ado.net Entity Data Model in Entity Framework.
  4. How to implement Entity Framework using Stored Procedure in Asp.net MVC Application Real Time Scenario.