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.
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.
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.
Step 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.
Name it CustomerController because all the request for Customer Class will be handled by Customer Controller.
Add a new class.
Declaring Customer class Properties:
- usingSystem.ComponentModel.DataAnnotations;
- namespaceEntityF.Models
- {
- publicclassCustomer
- {
-
- [Key]
- publicint Id
- {
- get;
- set;
- }
- publicstring Name
- {
- get;
- set;
- }
- publicstring Address
- {
- get;
- set;
- }
- }
- }
Now we will create a
DataContext class which will have db related information. We will create a class in model folder.
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.
- using System.Data.Entity;
- namespace EntityF.Models
- {
- public class DAL: DbContext
- {
-
- public DbSet < Customer > customer
- {
- get;
- set;
- }
- protected override void OnModelCreating(DbModelBuildermodelBuilder)
- {
-
- modelBuilder.Entity < Customer > ().ToTable("Customer");
- }
- }
- }
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:
- <connectionStrings>
- <add name="DAL"connectionString="Data Source=.;Initial Catalog=EnitySample;Integrated Security=True"providerName="System.Data.SqlClient" />
- </connectionStrings>
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 your User Form: - @model EntityF.Models.Customer
-
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
-
- <h2>Index</h2>
- <script src="~/Scripts/bootstrap.min.js">
- </script>
- <form action="~/Customer/Create"method="post">
- <div class="form-group">
- <label for="exampleInputCustomerName">Customer Name
- </label>
- <input type="text"class="form-control"id="txtCustomer"name="Name"placeholder="Enter your Name">
- </div>
- <div class="form-group">
- <label for="exampleInputAddress">Customer Address
- </label>
- <input type="text"class="form-control"id="txtCustomer"name="Address"placeholder="Password">
- </div>
- <button type="submit"class="danger">Submit
- </button>
- </form>
- <div></div>
-
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
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.
- USE[EnitySample]
- GO
-
- /****** Object: Table [dbo].[Customer] Script Date: 2/7/2016 10:40:19 AM ******/
- SET ANSI_NULLSON
- GO
-
- SET QUOTED_IDENTIFIERON
- GO
-
- SET ANSI_PADDINGON
- GO
-
- CREATE TABLE[dbo].[Customer](
- [ID][int]IDENTITY(1,1)NOTNULL,
- [Name][varchar](150)NOTNULL,
- [Address][varchar](150)NOTNULL,
- CONSTRAINT[PK_Customer]PRIMARYKEYCLUSTERED
- (
- [ID]ASC
- )WITH(PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON[PRIMARY]
- )ON[PRIMARY]
-
- GO
-
- SET ANSI_PADDINGOFF
- GO
Now we will create a private instance of Dbcontext class called DAL.
- private DAL _context;
- public CustomerController(DAL context)
- {
- _context = context;
- }
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.
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.
- [HttpPost]
- public ActionResult Create(Customer customer)
- {
- _context.customer.Add(customer);
- _context.SaveChanges();
- return RedirectToAction("Show");
-
- }
Now will write our Controller/Action link in the _layout page:
- <div class="navbar-collapse collapse">
- <ul class="navnavbar-nav">
- <li>@Html.ActionLink("Home", "Index", "Home")</li>
- <li>@Html.ActionLink("About", "About", "Home")</li>
- <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
- <li>@Html.ActionLink("Add Customer", "Index", "Customer")</li>
- </ul>
-
-
- public ActionResult Show()
- {
- List
- <Customer> customers = newList
- <Customer>();
- customers = _context.customer.ToList
- <Customer>();
- return View(customers);
-
- }
Now create a new view named
Show().
This View will strongly type of Ienumerable collection of type Customers.
- @usingEntityF.Models;
- @model IEnumerable
- <Customer>
-
-
- @{
- ViewBag.Title = "Show";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
-
- <h2>All list of Customer</h2>
- <table>
- <tr>
- <th>
- CustomerId
- </th>
- <th>Customer Name</th>
- <th>Customer Address</th>
- </tr>
-
- @{
- foreach (Customercustin Model)
- {
-
- <tr>
- <td>
- @cust.Id
- </td>
- <td>
- @cust.Name
-
- </td>
- <td>@cust.Address</td>
- <td>
- @*Edit link for the User to edit the Customer Information*@
- @Html.ActionLink("Edit", "Edit", "Customer", new { id = cust.Id }, null)
- </td>
- <td>
- @*Delete link for the User to delete the Customer Information*@
- @Html.ActionLink("Delete", "Delete", "Customer", new { id = cust.Id }, null)
- </td>
- </tr>
- }
- }
-
- </table>
- <a href="@Url.Content("~/Customer/Index")"style="text-align:left;color:#F3C632; text-decoration:none">New Customer
- </a>
- </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.
- @model EntityF.Models.Customer
-
- @{
- ViewBag.Title = "Edit";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
-
- <h2>Edit</h2>
- <script src="~/Scripts/bootstrap.min.js">
- </script>
- <form action="~/Customer/Save"method="post">
- <div class="form-group">
- <label for="exampleInputCustomerId">Customer Id
- </label>
- <input type="text"class="form-control"id="txtCustomer"value="@Model.Id"name="Id"placeholder="Enter your Name">
- </div>
- <div class="form-group">
- <label for="exampleInputCustomerName">Customer Name
- </label>
- <input type="text"class="form-control"id="txtCustomer"value="@Model.Name"name="Name"placeholder="Enter your Name">
- </div>
- <div class="form-group">
- <label for="exampleInputAddress">Customer Address
- </label>
- <input type="text"class="form-control"id="txtCustomer"value="@Model.Address"name="Address"placeholder="Password">
- </div>
- <button type="submit"class="danger">Submit
- </button>
- </form>
- <div></div>
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
Delete - @model EntityF.Models.Customer
-
- @{
- ViewBag.Title = "Delete";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
-
- <h2>Are you Sure do you want to delete this Customer</h2>
- <form action="~/Customer/Delete"method="post">
- <div class="form-group">
- <label for="exampleInputCustomerId">Customer Id
- </label>
- <input type="text"class="form-control"id="txtCustomer"value="@Model.Id"name="Id"placeholder="Enter your Name">
- </div>
- <div class="form-group">
- <label for="exampleInputCustomerName">Customer Name
- </label>
- <input type="text"class="form-control"id="txtCustomer"value="@Model.Name"name="Name"placeholder="Enter your Name">
- </div>
- <div class="form-group">
- <label for="exampleInputAddress">Customer Address
- </label>
- <input type="text"class="form-control"id="txtCustomer"value="@Model.Address"name="Address"placeholder="Password">
- </div>
- <button type="submit"class="danger">Delete
- </button>
- </form>
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
Now we will create our HttpGet and HttpPost for edit and Delete operations.
- public ActionResult Edit(int ? id)
- {
- Customer customer = newCustomer();
- customer = _context.customer.Where(a => a.Id == id).Single < Customer > ();
- return View("Edit", customer);
- }
- [HttpGet]
- public ActionResult Delete(int ? id)
- {
- Customer customer = newCustomer();
- customer = _context.customer.Where(a => a.Id == id).Single < Customer > ();
- return View("Delete", customer);
- }
- [HttpPost]
- public ActionResult Save(Customer customer)
- {
- Customer cust = _context.customer.Where(c => c.Id == customer.Id).Single < Customer > ();
- cust.Name = customer.Name;
- cust.Address = customer.Address;
- _context.SaveChanges();
- return RedirectToAction("Show");
- }
- [HttpPost]
- public ActionResult Delete(Customer customer)
- {
- Customer cust = newCustomer();
- cust = _context.customer.Where(c => c.Id == customer.Id).Single < Customer > ();
- _context.customer.Remove(cust);
- _context.SaveChanges();
- return RedirectToAction("Show");
- }
SO now we are ready to go run the application.
Put the break points so that we can debug our program.
Now click on add Customer.
Controller hits the action method called Index.
Now Index view will be returned.
Insert your Customer Information and press Submit.
Create action method is Hit with all the information Entered by the User.
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.
- 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.
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.
The list of Customer inserted has been retrieved from the db. Let’s insert some more Customers.
Now we will perform our Edit operation so we will click on Edit option for 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.
- 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.
Now the user will edit the Information of the Customer as shown below:
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.
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.
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.
Now we will 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.
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: