Entity framework is part of .NET Framework it generates necessary database command that execute connection with database without using the standard SQL queries. To expand our understanding on how Entity Framework works. I created an ASP.NET MVC web application to share what I’ve learned. For beginners like me hopes this helps.

Image below is the table I created for this project. I name the database as Employee_Listing and for the table I name it as Table. If this is your first time to create a database visit this thread Create Database using Visual Studio for detailed instruction on how I created this database.

Application Final UI Output:

Final Output

Let’s Start:

Note: If this is your first time creating a project visit this thread How to Start with ASP.NET MVC Application for tutorial on creating a new project in ASP.Net MVC Web Application.

for tutorial on creating a new project in ASP.Net MVC Web Application. For adding Entity Framework using NuGet Package Manager use this thread Adding Entity Framework using NuGet Package Manager .

. For ASP.NET MVC Basic folder structure visit this thread Default ASP.NET MVC file structure

1. I assume you have already created a project and added entity framework if not visit the link from the note above . Now add ADO.NET Entity Data Model. I prefer adding it to my Model folder. To add, right click on the Models folder, click Add and choose New Item.

Add ADO.NET Entity Data Model

2. From Add New Item window select Data under Visual C# from the left pane and choose ADO.NET Entity Data Model from the middle pane. Then name your model. In my case I name it as Employee_Listing.

Name Entity Model

3. In the next window select option Generate from Database and then click “Next”

Generate from database

4. Create new connection by simply clicking New Connection button

Create New Connection

5. Choose Data source for your database. In my case it is Microsoft SQL Server then click “Continue”.

Choose SQL Server

6. In connection properties choose your Server name and select your Database name as shown below.

Choose Server and Database Name

7. To test connection of your database click “Test Connection” button. Then press “OK”.

Test Connection

8. Click “Next” to proceed.

Entity Model Wizard

9. Choose Table you want to add to your project.

Choose Table

10. If security warning pop-up select “OK”.

Security Warning

11. Visual Studio will create edmx file with the Table model for your database.

Project View

12. The image below is the full screenshot of my Models folder.

Models folder

13. Table.cs is the class Model of the Table I added with ADO.NET Entity Data Model.

Table.cs

Code inside Table.cs

This is our Entity Model class. I added [Required] attribute to every property declared from this model for Data Annotation to be used for model binding to our UI form inputs.

//------------------------------------------------------------------------------ // // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // //------------------------------------------------------------------------------ namespace MVC_Data_Entity.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public partial class Table { public int Id { get; set; } [Required] public string Employee_Name { get; set; } [Required] public string Emp_Address { get; set; } [Required] public string Emp_Number { get; set; } [Required] public string Emp_Position { get; set; } } }

Let’s start with the coding part

We are going to use the default Controller for MVC Template which is HomeController. Located under HomeController folder and its default view located under Views->Home->index.cshtml.

Solution Explorer

1. Create a view for your application. Open Index.cshtml file refer to highlighted text shown in the image above.

Index.cshtml

Create a form using html helper to bind our model.

@using MVC_Data_Entity.Models -> gain access to our Models folder

folder @model Table -> gain access to our actual Model class which is the class Table inside Table.cs.

<script src=”~/Scripts/jquery-1.10.2.min.js”></script> -> Add JQuery script.

Get_Data() -> JavaScript function use for transferring data to our view from our Controller

Delete(id) -> JavaScript function that call delete function in controller to delete specific data from our database

Edit(id) – > JavaScript function that call select function from our controller and fill form with the existing data.

table_data(data) -> This is a table design JavaScript function to be fill in our table without a whole page loading.

@Html.ValidationSummary -> Show validation error base on the [required] attribute we set in our Table Model.

@Html.ValidationMessageFor -> Show validation error for specific inputs.

Code:

@using MVC_Data_Entity.Models @model Table @{ ViewBag.Title = "Home Page"; } <div class=""> <h3>MVC Data Entity</h3> @using (Html.BeginForm("Index", "Home", FormMethod.Post, new {@class="form-horizontal",role="form" })) { <fieldset> @Html.ValidationSummary(true, "", new {@class="text-danger" }) <div class="form-group"> @Html.LabelFor(m => m.Employee_Name, new {@class="col-lg-2 control-label" }) <div class="col-lg-10"> @Html.TextBoxFor(m => m.Employee_Name, new { @class="form-control"}) @Html.ValidationMessageFor(m => m.Employee_Name, "", new { @class="text-danger"}) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Emp_Address, new { @class = "col-lg-2 control-label" }) <div class="col-lg-10"> @Html.TextBoxFor(m => m.Emp_Address, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Emp_Address, "", new { @class="text-danger"}) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Emp_Number, new { @class = "col-lg-2 control-label" }) <div class="col-lg-10"> @Html.TextBoxFor(m => m.Emp_Number, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Emp_Number, "", new { @class="text-danger"}) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Emp_Position, new { @class = "col-lg-2 control-label" }) <div class="col-lg-10"> @Html.TextBoxFor(m => m.Emp_Position, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Emp_Position, "", new { @class="text-danger"}) </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </fieldset> } <button class="btn btn-primary" onclick="Get_Data()">Get Data</button> <table class="table"> <thead> <tr> <th>Employee Name</th> <th>Employee Address</th> <th>Employee Number</th> <th>Employee Position</th> <th>Option</th> </tr> </thead> <tbody id="Table_data"> </tbody> </table> </div> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script> $(document).ready(function () { Get_Data(); //fill table }) var controller_url = '@Url.Action("Home", "GetData")'; function Get_Data() { $.post('@Url.Action("GetData", "Home")', function (data) { var parse_data = JSON.parse(data); $("#Table_data").html(table_data(parse_data)); }); } function Delete(id) { $.post('@Url.Action("Delete", "Home")', {'id':id},function (data) { alert(data); Get_Data(data); }); } function Edit(id) { $.post('@Url.Action("Select_data_for_edit","Home")', { 'id': id }, function (data) { var parse_data = JSON.parse(data); $("#Employee_Name").val(parse_data.Employee_Name.toString().trim()); $("#Emp_Address").val(parse_data.Emp_Address.toString().trim()); $("#Emp_Number").val(parse_data.Emp_Number.toString().trim()); $("#Emp_Position").val(parse_data.Emp_Position.toString().trim()); }); } function table_data(data) { var result = ""; for (var i = 0; i < data.length; i++) { result += "<tr>"; result += "<td>" + data[i].Employee_Name + "</td>"; result += "<td>" + data[i].Emp_Address + "</td>"; result += "<td>" + data[i].Emp_Number + "</td>"; result += "<td>" + data[i].Emp_Position + "</td>"; result += "<td><button id='" + data[i].Id + "' class='btn btn-default' onclick='Edit(this.id)'>Edit</button><button id='" + data[i].Id + "' class='btn btn-default' onclick='Delete(this.id)'>Delete</button></td>"; result += "</tr>"; return result; } </script>

2. Next open your HomeController. Let’s create and apply CRUD (Create, Read, Update and Delete) which is the basic function for most of the systems.

HomeController.cs

Function summary for HomeController

Index() – > Load default view

Index(Table model) -> received post request from our UI form.

GetData() -> Get all data from our table.

Select_data_for_edit(int id) – > Select specific data by id from our database table

Delete(int id) -> Delete data from table by id

Update()-> Update data entry from database table

Insert_data(Table model) -> Insert new entry to database table

Code:

using MVC_Data_Entity.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data; using Newtonsoft.Json; namespace MVC_Data_Entity.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(Table model) { if (!ModelState.IsValid) { return View(); } Insert_data(model); return View(); } public string GetData() { List