Getting Started With Entity Framework

Entity Framework

Entity Framework is an ORM tool. ORM stands for Object Relational Mapper, as the name specifies it  maps our business models with our db types.

Basically we generally uses SQL statement to talk with db. We write our repetitive code to perform CRUD operations and fire the queries against the db. To perform this operation we have to check the db schema table information and make the queries in db first. So there is a huge lot of disturbance for a developer to write code and also look for the db table structure to perform operations.

structure to perform operation

Imagine how it would be done if our business model could directly talk with DB schema; i.e., that’s is where ORM comes into picture. It maps our Class objects with DB tables’ types and now we can easily query our model rather than query our database.

We can fire asynclinq queries, it keeps us from repeated code and compiled time errors which was not in the case of the query.

ORM

Entity Framework is Microsoft ORM tool for mapping our Business objects with Database schema types. It has three approaches:

  • Wizard approach
  • POCO Classes (plain old CLR objects)
  • Code first

I won’t be going to the details of wizard and poco classes. I will be unleashing the code at first approach from scratch. So stay tuned.

Step 1: Create a new Project.

Step 2: Select Web.

Step 3: ASP.NET WEB Application.

ASP.NET WEB Application

Step 4: MVC 4,

MVC 4

So we are going to performa CRUD operation. CRUD stands for Create, Read, Update, and Delete. So let's get started.

Create Controller.

Create Controller

Name it CustomerController because all the request for Customer Class will be handled by Customer Controller.

add Controller

Add a new class.

Add a new class

Declaring Customer class Properties:

  1. usingSystem.ComponentModel.DataAnnotations;  
  2. namespaceEntityF.Models  
  3. {  
  4.     publicclassCustomer  
  5.     {  
  6.         //Entity Framework Id is by default assumed as primary key  
  7.         [Key]  
  8.         publicint Id  
  9.         {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         publicstring Name  
  14.         {  
  15.             get;  
  16.             set;  
  17.         }  
  18.         publicstring Address  
  19.         {  
  20.             get;  
  21.             set;  
  22.         }  
  23.     }  
  24. }  
Now we will create a DataContext class which will have db related information. We will create a class in model folder.

Class

Inherit the class from DbContext. DbContext gives the class all the setup that is needed to do the operation you want to do with DB Schema, or we can say it allows us to communicate with a DB.
  1. using System.Data.Entity;  
  2. namespace EntityF.Models  
  3. {  
  4.     public class DAL: DbContext  
  5.     {  
  6.         //glue code   
  7.         public DbSet < Customer > customer  
  8.         {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         protected override void OnModelCreating(DbModelBuildermodelBuilder)  
  13.         {  
  14.             //mapping with the Customer Table  
  15.             modelBuilder.Entity < Customer > ().ToTable("Customer");  
  16.         }  
  17.     }  
  18. }  
So now Dal class wants to know which database we want him to communicate with so we need to specify the connection string.

Note: The name of the class should be same as connection string name as shown below:
  1. <connectionStrings>  
  2.    <add name="DAL"connectionString="Data Source=.;Initial Catalog=EnitySample;Integrated Security=True"providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  
relation

DB context acts as GLUE between Models and DB tables. I.e. the business properties to the table fields.

So now we have setup our dbcontext class which will communicate with db and perform our CRUD operations.

Create Operation

Now we will create our Razor view where the user will enter his/her information which will be inserted into the db.

Create Operation

Create your User Form:
  1. @model EntityF.Models.Customer  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8.   
  9. <h2>Index</h2>  
  10. <script src="~/Scripts/bootstrap.min.js">  
  11. </script>  
  12. <form action="~/Customer/Create"method="post">  
  13.     <div class="form-group">  
  14.         <label for="exampleInputCustomerName">Customer Name  
  15.         </label>  
  16.         <input type="text"class="form-control"id="txtCustomer"name="Name"placeholder="Enter your Name">  
  17.         </div>  
  18.         <div class="form-group">  
  19.             <label for="exampleInputAddress">Customer Address  
  20.             </label>  
  21.             <input type="text"class="form-control"id="txtCustomer"name="Address"placeholder="Password">  
  22.             </div>  
  23.             <button type="submit"class="danger">Submit  
  24.             </button>  
  25.         </form>  
  26.         <div></div>  
  27.   
  28.         @section Scripts {  
  29.         @Scripts.Render("~/bundles/jqueryval")  
  30. }  
I have created my database named EnitySample in mylocalsqlserver and created a table class Customer which has three filed ID, NAME and ADDRESS.

Id here is identity field.
  1. USE[EnitySample]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Customer]    Script Date: 2/7/2016 10:40:19 AM ******/  
  5. SET ANSI_NULLSON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIERON  
  9. GO  
  10.   
  11. SET ANSI_PADDINGON  
  12. GO  
  13.   
  14. CREATE TABLE[dbo].[Customer](  
  15.     [ID][int]IDENTITY(1,1)NOTNULL,  
  16.     [Name][varchar](150)NOTNULL,  
  17.     [Address][varchar](150)NOTNULL,  
  18. CONSTRAINT[PK_Customer]PRIMARYKEYCLUSTERED  
  19. (  
  20.     [ID]ASC  
  21. )WITH(PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON[PRIMARY]  
  22. )ON[PRIMARY]  
  23.   
  24. GO  
  25.   
  26. SET ANSI_PADDINGOFF  
  27. GO  
Dbcontext
Now we will create a private instance of Dbcontext class called DAL.
  1. private DAL _context;  
  2. public CustomerController(DAL context)  
  3. {  
  4.    _context = context;  
  5. }  
We will use _context class all over this controller rather than creating the DAL object in each method. In order to implement this we need to inject the dependency. So you need to install two packages. 
  • Unity
  • Unity MVC 4

Once you are done with installing packages, now we will create our Create Action Method in the Controller which will be responsible for inserting Customer Information into the db.

What we want to do ahead is once our data gets inserted into the database the inserted data should be shown into the view (Read) and we should give edit and delete functionality. So once the changes have been done to the db we will move to a different action called show which will show the inserted details.

  1. [HttpPost]  
  2. public ActionResult Create(Customer customer)  
  3. {  
  4.    _context.customer.Add(customer);  
  5.    _context.SaveChanges();  
  6.    return RedirectToAction("Show");  
  7.   
  8. }  
Now will write our Controller/Action link in the _layout page:
  1. <div class="navbar-collapse collapse">  
  2.     <ul class="navnavbar-nav">  
  3.         <li>@Html.ActionLink("Home""Index""Home")</li>  
  4.         <li>@Html.ActionLink("About""About""Home")</li>  
  5.         <li>@Html.ActionLink("Contact""Contact""Home")</li>  
  6.         <li>@Html.ActionLink("Add Customer""Index""Customer")</li>  
  7.     </ul>  
  8.   
  9. //Show Action Result will responsible for extracting all the information to the User.  
  10. public ActionResult Show()  
  11. {  
  12.     List  
  13.         <Customer> customers = newList  
  14.         <Customer>();  
  15.             customers = _context.customer.ToList  
  16.          <Customer>();  
  17.             return View(customers);  
  18.   
  19. }  
Now create a new view named Show().

This View will strongly type of Ienumerable collection of type Customers.
  1. @usingEntityF.Models;  
  2. @model IEnumerable  
  3. <Customer>  
  4.   
  5.   
  6. @{  
  7.     ViewBag.Title = "Show";  
  8.     Layout = "~/Views/Shared/_Layout.cshtml";  
  9. }  
  10.   
  11.   
  12.     <h2>All list of Customer</h2>  
  13.     <table>  
  14.         <tr>  
  15.             <th>  
  16.                 CustomerId  
  17.         </th>  
  18.             <th>Customer Name</th>  
  19.             <th>Customer Address</th>  
  20.         </tr>  
  21.   
  22.         @{  
  23.             foreach (Customercustin Model)  
  24.             {  
  25.   
  26.                 <tr>  
  27.                     <td>  
  28.                         @cust.Id  
  29.                     </td>  
  30.                 <td>  
  31.                     @cust.Name  
  32.   
  33.                 </td>  
  34.                 <td>@cust.Address</td>  
  35.                 <td>  
  36.                     @*Edit link for the User to edit the Customer Information*@  
  37.                     @Html.ActionLink("Edit""Edit""Customer"new { id = cust.Id }, null)  
  38.                 </td>  
  39.             <td>  
  40.                 @*Delete link for the User to delete the Customer Information*@  
  41.                 @Html.ActionLink("Delete""Delete""Customer"new { id = cust.Id }, null)  
  42.             </td>  
  43.         </tr>  
  44.     }  
  45. }  
  46.   
  47.     </table>  
  48.     <a href="@Url.Content("~/Customer/Index")"style="text-align:left;color:#F3C632; text-decoration:none">New Customer  
  49.     </a>  
  50. </td>  
Once we are done with our Show view, let’s create the Edit and Delete which will be same as our Index razor view.

Edit: This view will contains the edit view for the Customer, it is strongly typed of Customer object.
  1. @model EntityF.Models.Customer  
  2.   
  3. @{  
  4. ViewBag.Title = "Edit";  
  5. Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8.   
  9. <h2>Edit</h2>  
  10. <script src="~/Scripts/bootstrap.min.js">  
  11. </script>  
  12. <form action="~/Customer/Save"method="post">  
  13.     <div class="form-group">  
  14.         <label for="exampleInputCustomerId">Customer Id  
  15.         </label>  
  16.         <input type="text"class="form-control"id="txtCustomer"value="@Model.Id"name="Id"placeholder="Enter your Name">  
  17.         </div>  
  18.         <div class="form-group">  
  19.             <label for="exampleInputCustomerName">Customer Name  
  20.             </label>  
  21.             <input type="text"class="form-control"id="txtCustomer"value="@Model.Name"name="Name"placeholder="Enter your Name">  
  22.             </div>  
  23.             <div class="form-group">  
  24.                 <label for="exampleInputAddress">Customer Address  
  25.                 </label>  
  26.                 <input type="text"class="form-control"id="txtCustomer"value="@Model.Address"name="Address"placeholder="Password">  
  27.                 </div>  
  28.                 <button type="submit"class="danger">Submit  
  29.                 </button>  
  30.             </form>  
  31.             <div></div>  
  32.             <div>  
  33. @Html.ActionLink("Back to List""Index")  
  34. </div>  
Delete
  1. @model EntityF.Models.Customer  
  2.   
  3. @{  
  4. ViewBag.Title = "Delete";  
  5. Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8.   
  9. <h2>Are you Sure do you want to delete this Customer</h2>  
  10. <form action="~/Customer/Delete"method="post">  
  11.     <div class="form-group">  
  12.         <label for="exampleInputCustomerId">Customer Id  
  13.         </label>  
  14.         <input type="text"class="form-control"id="txtCustomer"value="@Model.Id"name="Id"placeholder="Enter your Name">  
  15.         </div>  
  16.         <div class="form-group">  
  17.             <label for="exampleInputCustomerName">Customer Name  
  18.             </label>  
  19.             <input type="text"class="form-control"id="txtCustomer"value="@Model.Name"name="Name"placeholder="Enter your Name">  
  20.             </div>  
  21.             <div class="form-group">  
  22.                 <label for="exampleInputAddress">Customer Address  
  23.                 </label>  
  24.                 <input type="text"class="form-control"id="txtCustomer"value="@Model.Address"name="Address"placeholder="Password">  
  25.                 </div>  
  26.                 <button type="submit"class="danger">Delete  
  27.                 </button>  
  28.             </form>  
  29.             <div>  
  30. @Html.ActionLink("Back to List""Index")  
  31. </div>  
Now we will create our HttpGet and HttpPost for edit and Delete operations.
  1. public ActionResult Edit(int ? id)  
  2. {  
  3.     Customer customer = newCustomer();  
  4.     customer = _context.customer.Where(a => a.Id == id).Single < Customer > ();  
  5.     return View("Edit", customer);  
  6. }  
  7. [HttpGet]  
  8. public ActionResult Delete(int ? id)  
  9. {  
  10.     Customer customer = newCustomer();  
  11.     customer = _context.customer.Where(a => a.Id == id).Single < Customer > ();  
  12.     return View("Delete", customer);  
  13. }  
  14. [HttpPost]  
  15. public ActionResult Save(Customer customer)  
  16. {  
  17.     Customer cust = _context.customer.Where(c => c.Id == customer.Id).Single < Customer > ();  
  18.     cust.Name = customer.Name;  
  19.     cust.Address = customer.Address;  
  20.     _context.SaveChanges();  
  21.     return RedirectToAction("Show");  
  22. }  
  23. [HttpPost]  
  24. public ActionResult Delete(Customer customer)  
  25. {  
  26.     Customer cust = newCustomer();  
  27.     cust = _context.customer.Where(c => c.Id == customer.Id).Single < Customer > ();  
  28.     _context.customer.Remove(cust);  
  29.     _context.SaveChanges();  
  30.     return RedirectToAction("Show");  
  31. }  
SO now we are ready to go run the application.

Put the break points so that we can debug our program.

run application

Now click on add Customer.

Controller hits the action method called Index.

Controller
Now Index view will be returned.

Index view
Insert your Customer Information and press Submit.

Create action method is Hit with all the information Entered by the User.

Create action method

 

context.customer.Add(customer) will add the Customer object in memory once the _context.savechanges has been done than the data is saved in the database.

database

  • Our Linq queries are fired against the database you can verify the same by using sql profiler or other tools.
  • Entity framework uses ADO.NET.
  • Full ORM to map objects to Code.
  • Async queries.
  • Repeated data access code.

access code

Once the Create Customer operation has been complete Show Action method will be hit and here we perform a LINQ query to get Collection of Customer from the database.

perform a LINQ query

The list of Customer inserted has been retrieved from the db. Let’s insert some more Customers.

list of Customer

Now we will perform our Edit operation so we will click on Edit option for SailleshPawar.

SailleshPawar

So now Edit Action method got hits and Id 1 which was generated for Saillesh was passed to the method, in this method we will first create an object of Customer and extract the details of Customer having id and pass the same to Edit view.

  1. customer = _context.customer.Where(a =>a.Id == id).Single<Customer>();  
This is a LINQ query for retrieving a single customer which contains the id that has been passed to the action method.

single Customer

Now the user will edit the Information of the Customer as shown below:

Information of the Customer

Press Submit

Press Submit

All the new updated information will be passed to the Customer object and now we will first retrieve the old value of the Customer and assign the new value to the same object and then save the changes to the database.

Output

Now you can see above SailleshPawar has been updated to VirenderPawar and Address Mumbai has been updated to Dehradun.

Now we will perform delete operation and will try to delete AnkitNegi from the Customer List.

Code

As we hit delete link the id of the Customer Ankit will be passed to Action Method. Here also we will do the same thing as we did in Edit function retrieving value of the Customer with ID 3 and passing the Customer object to the Delete View.

run

Now we will press delete.

press delete

And as we can see above all the Customer information is passed to Customer object. Here will retrieve all the customers and then remove this customer from the list and then make save changes to the database.

list

Now we can see above that we have successfully deleted the Customer details from the database. So we can see how easily we have performed our CRUD operations without writing a single SQL query by ourselves. We have strongly typed queries and if try to write a wrong LINQ query we will prompted with an error. I hope this article was helpful, I would be happy and will feel appreciated if you could comment and help me in doing better. 
 
Read more articles on Entity Framework:

Up Next
    Ebook Download
    View all
    Learn
    View all