Employee System using ASP.net MVC and Entity Framework


Looking for sample source code in ASP.net MVC and Entity Framework? Check out this article to find one such sample application using Asp.Net MVC and Entity Framework. This is an employee system application coded using Asp.Net MVC and entity framework.

Employee System is basic application build from the ASP.net MVC and Entity Framework. It has CRUD operation like Create, Edit, Delete and View Detail functionality. I have built the same application with static data in my previous post, now I am taking one step ahead to use the database to store our data. To work with database I will be using Entity Framework which was introduced with .Net 3.5 SP1 and had much improvement in .Net 4.

Below is the screen shot which we will be building today.

Employee System Application using ASP.net MVC

Figure 1


You'll learn today



1. How to use EF (Code First) approach with ASP.net MVC application

Please read my first article to know more about the MVC and how to create the MVC based application. In this post I will be using the same view but modified controller and model with EF (Entity Framework) support.

To complete this post I will be using some parts of my first post as I am building this application on top of that.

Code First Development with EF



As I mentioned controller and view are almost same as first application but with some changes in controller and the changes are done on Model to use the code first approach of EF.

Let's see our modified model class which is POCO class (Plain Old CLR Objects). It is simple class without extending any class or implementing any interface.

In Code first we don't have to create a database first instead we can build the model which will define the domain model objects for our application. Our Employee application is simple so as our model will be simple too and it's shown below. I have not change the annotation which we were using for our validation.

Model



Employee.cs



using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace EmployeeInfo.Models
{
public class Employee
{
[Required(ErrorMessage="Employee ID is Required")]
[Display(Name="Employee ID")]
public int EmployeeID { get; set; }

[Display(Name = "Employee Name")]
public string EmpName { get; set; }

[Display(Name = "Employee Address")]
public string EmpAddress { get; set; }

[Display(Name = "Employee Phone")]
public string EmpPhone { get; set; }

[Display(Name = "Employee Salary")]
[Range(1000,5000,ErrorMessage="The salary should be in between {1} and {2}")]
[DataType(DataType.Currency)]
public double EmpSalary { get; set; }

}


Context Class to Handle Database Persistence



We have created our POCO model class, now let's create a context class that we can use to handle the retrieval/persistence of Employee instances from database. I named as EmployeeDBContext and it is derived from DbContext class. It has one property which exposes Employee Data Set.

DbContext and DbSet are key in Entity Framework, both are in System.Data.Entity namespace. You need to add the reference if it is not added.


using System.Data.Entity;

public class EmployeeDBContext : DbContext
{
public DbSet Employees { get; set; }

}


That's all we need to build our application, now you will be thinking where the database is and how it will be mapped to our model.Let's take a look into those concept below.

Convention Based Mapping



EF "Code First" supports a convention over configuration approach that enables you to do mapping using conventions instead of doing explicit configuration.

In our application, Model Employee class will be the database table under your database. EmployeeDBContext class will be map its Employees to "Employee" table within database. Each row in the Employee table will map to an instance of our Employee Class.

You just need to mention what type of database you are using and provider. Here I am using the SQL Server Compact database. Here we are just going to put the connection string in Web.Config file as shown below



providerName="System.Data.SqlServerCe.4.0"/>



In connection string I mentioned to use the Employees.sdf (SQL Server Compact Database) under the APP_DATA folder.

When you run the application if the database is not there it will create the Database and Database Table using the model objects class.

Modified Controller



Controller has been rewritten to use the EF "Code First" fluent API to create, retrieve, find and save the data in database.

EmployeeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EmployeeInfo.Models;

namespace EmployeeInfo.Controllers
{
public class EmployeeController : Controller
{
EmployeeDBContext dbContext = new EmployeeDBContext();
//
// GET: /Employee/

public ActionResult Index()
{
return View(dbContext.Employees.ToList());
}
}
}

To get all the employees from the database the EF gives all the data from model object as shown above. As mentioned EF has the mapping to the table and each instance of model is row and it will return the list of employees as shown above

Views



We have two important pieces in place i.e. Controller and Model. Now we need UI which can display the List of Employees with some Actions Links. In MVC, View is used to display the UI components and renders the HTML output.

In MVC the view has the same name as your controller action has as per the convention which is really handy. Index is the controller action so we will have index.cshtml as View. If you have controller then in Visual Studio 2012 right click on the Index action result, it will give you context menu to add view as shown below

Employee System Application using ASP.net MVC

Click on Add View menu and it will open the box as shown below with Index as the View name by convention. Choose View Engine as Razor as we will be focusing on this engine in this tutorial.

Select the Create a strongly-typed view as we will be using Model which is already described above. You can leave layout manager empty or choose one which you want to use in your application as shown below.

Employee System Application using ASP.net MVC

It will create Index.cshtml view page.

Index.cshtml




@using EmployeeInfo.Models

@model IEnumerable<Employee>
@{

Layout = @Url.Content("~/Views/Shared/_Layout.cshtml");
}

<!DOCTYPE html>

<html>
<head>
<title>Index</title>
</head>
<body>

<div>
@* @MyHelpers.Employees(Model) *@
<h1>Employee Information</h1>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table border="1" style="background-color:#b6ff00;">
<thead>
<tr>
<th class="th">
@Html.Label("Employee Id")
</th>
<th class="th">
@Html.Label("Employee Name")
</th>
<th class="th">
@Html.Label("Employee Address")
</th>
<th class="th">
@Html.Label("Employee Phone")
</th>
<th class="th">
@Html.Label("Employee Salary")
</th>
<th>
@Html.Label("Action")
</th>
</tr>
</thead>
@foreach(var emp in Model){
<text>

<tr>
<td>
@emp.EmployeeID
</td>
<td>
@emp.EmpName
</td>
<td>
@emp.EmpAddress
</td>
<td>
@emp.EmpPhone
</td>
<td>
($@emp.EmpSalary)
</td>
<td>
@Html.ActionLink("Edit", "Edit",new { id = @emp.EmployeeID })
@Html.ActionLink("Delete", "Delete",new { id = @emp.EmployeeID })
@Html.ActionLink("Details", "Details", new { id = @emp.EmployeeID })
</td>
</tr>

</text>
}
</table>
</div>

</body>
</html>



Let's take one step ahead and finish all the actions in controller class for Create, Edit, Delete and Details.

On Create

Logically when we call the create action it should add the employee in our list and display the results with the new data.

On Edit

On edit we are going to edit the details of the employee except its ID. Here we have the static data so i am removing and adding the updated data in our list for simplicity.

On Delete
On Delete action we will be removing the employee from the list and go back to the list page with updated data.

On Details

Detail View is just to display the employee information in form manner instead as list.

You can update the project as per your requirement and to learn different aspects of the MVC model here.

In all of the scenarios I have used LINQ to query the data from the List as I like LINQ now.

Controller Class EmployeeController.cs




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EmployeeInfo.Models;

namespace EmployeeInfo.Controllers
{
public class EmployeeController : Controller
{
EmployeeDBContext dbContext = new EmployeeDBContext();
//
// GET: /Employee/

public ActionResult Index()
{
return View(dbContext.Employees.ToList());
}

//
// GET: /Employee/Details/Id

public ActionResult Details(Int32 id = 0)
{

Employee emp = dbContext.Employees.Find(id);
if (emp != null)
{
return View(emp);
}
else
{
return HttpNotFound("Employee Not found !!!");
}
}

// GET: /Employee/Create
public ActionResult Create()
{
return View();
}

//POST :/Employee/Create
[HttpPost]
public ActionResult Create(Employee emp)
{
if (ModelState.IsValid)
{
dbContext.Employees.Add(emp);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
return View(emp);
}

//POST :/Employee/Delete
[HttpDelete]
public ActionResult Delete(Int32 id)
{
Employee emp = dbContext.Employees.Find(id);
if (emp != null)
{
dbContext.Employees.Remove(emp);
dbContext.SaveChanges();
//dbContext.Empployees.Remove(emp)
return RedirectToAction("Index");
}
else
{
return HttpNotFound("Employee Not found !!!");
}

}

//Get: /Employee/Edit
[HttpPost]
public ActionResult Edit(Employee emp)
{
if (ModelState.IsValid)
{
dbContext.Entry(emp).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
return View(emp);
}

//POST: /Employee/Edit/1
[HttpGet]
public ActionResult Edit(Int32 id)
{
Employee emp = dbContext.Employees.Find(id);
if (emp != null)
{
return View(emp);
}
else
{
return HttpNotFound("Employee Not found !!!");
}
}
}
}



View Classes



Create.cshtml




@model EmployeeInfo.Models.Employee

@{
Layout = @Url.Content("~/Views/Shared/_Layout.cshtml");
}

<!DOCTYPE html>

<html>
<head>
<title>Create</title>
<script type="text/javascript" src="../../Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.js"></script>
</head>
<body>
<div>
<h2>Employee Detail</h2>
</div>
@using(@Html.BeginForm()){
<p> @Html.ValidationSummary(true,"Please fix the following errors") </p>
<div>
<div class="editor-label">
@Html.LabelFor(m => m.EmployeeID)
</div>
<div class="editor-field">
@Html.EditorFor(m =>m.EmployeeID)
@Html.ValidationMessageFor(m => m.EmployeeID)
</div>

<div class="editor-label">
@Html.LabelFor(m => m.EmpName)
</div>
<div class="editor-field">
@Html.EditorFor(m =>m.EmpName)
@Html.ValidationMessageFor(m => m.EmpName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.EmpAddress)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.EmpAddress)
@Html.ValidationMessageFor(m => m.EmpAddress)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.EmpPhone)
</div>
<div class="editor-field">
@Html.EditorFor(m =>m.EmpPhone)
@Html.ValidationMessageFor(m => m.EmpPhone)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.EmpSalary)
</div>
<div class="editor-field">
@Html.EditorFor(m =>m.EmpSalary)
@Html.ValidationMessageFor(m => m.EmpSalary)
</div>
</div>
<p>
<input type="submit" value="Create" />
</p>
}
<p>
@Html.ActionLink("Back to List", "Index");
</p>
</body>
</html>



When you click on the Create New link on the first page, It will call the Create action from the controller and render the View associated with that controller i.e. Create.cshtml. The HTML output will look like as shown below.

Employee System Application using ASP.net MVC

You can provide the data and hit create button which will call the POST action i.e. public ActionResult Create(Employee emp) which will pass the Employee form data back to your controller.

Edit.cshtml




@model EmployeeInfo.Models.Employee

@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}


<head>
<title>Edit</title>
<script type="text/javascript" src="../../Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.js"></script>
</head>
<body>
<div>
<h2>Edit Employee Detail</h2>
</div>
@using(@Html.BeginForm()){
<p> @Html.ValidationSummary(true,"Please fix the following errors") </p>
<div>
<div class="editor-label">
@Html.LabelFor(m => m.EmployeeID)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.EmployeeID, new { @readonly = "readonly" })
@Html.ValidationMessageFor(m => m.EmployeeID)
</div>

<div class="editor-label">
@Html.LabelFor(m => m.EmpName)
</div>
<div class="editor-field">
@Html.EditorFor(m =>m.EmpName)
@Html.ValidationMessageFor(m => m.EmpName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.EmpAddress)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.EmpAddress)
@Html.ValidationMessageFor(m => m.EmpAddress)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.EmpPhone)
</div>
<div class="editor-field">
@Html.EditorFor(m =>m.EmpPhone)
@Html.ValidationMessageFor(m => m.EmpPhone)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.EmpSalary)
</div>
<div class="editor-field">
@Html.EditorFor(m =>m.EmpSalary)
@Html.ValidationMessageFor(m => m.EmpSalary)
</div>
</div>
<p>
<input type="submit" value="Edit" />
</p>
}
<p>
@Html.ActionLink("Back to List", "Index");
</p>
</body>
</html>



When you click on the Edit link for that employee, It will call the GET edit action from the controller and render the View associated with that controller i.e. Edit.cshtml. The HTML output will look like as shown below.

Employee System Application using ASP.net MVC

You can update the data and hit Edit button which will call the POST action i.e. public ActionResult Edit(Employee emp) which will pass the Employee form data back to your controller.

Details.cshtml





@model EmployeeInfo.Models.Employee

@{
Layout = @Url.Content("~/Views/Shared/_Layout.cshtml");
}

<!DOCTYPE html>

<html>
<head>
<title>Details</title>
</head>
<body>
<h2>Employee Details for @Model.EmpName</h2>
<div>
<pre class="editor-label">@Html.LabelFor(m => m.EmployeeID) : @Html.TextBox("EmployeeID", Model.EmployeeID, new { @readonly = "readonly" })</pre>
<pre class="editor-label">@Html.LabelFor(m => m.EmpName) : @Html.TextBox("EmployeeID", Model.EmpName, new { @readonly = "readonly" })</pre>
<pre class="editor-label">@Html.LabelFor(m => m.EmpAddress) : @Html.TextBox("EmployeeID", Model.EmpAddress, new { @readonly = "readonly" })</pre>
<pre class="editor-label">@Html.LabelFor(m => m.EmpPhone) : @Html.TextBox("EmployeeID", Model.EmpPhone, new { @readonly = "readonly" })</pre>
<pre class="editor-label">@Html.LabelFor(m => m.EmpSalary) : @Html.TextBox("EmployeeID", Model.EmpSalary, new { @readonly = "readonly" })</pre>

</div>
<p>
@Html.ActionLink("Back to List", "Index")
</p>
</body>
</html>



When you click on the Details link for that employee, It will call the GET detail action from the controller and render the View associated with that controller i.e. Details.cshtml. The HTML output will look like as shown below.

Employee System Application using ASP.net MVC


Comments

Guest Author: jayakumar07 Oct 2012

hi
Kapil
post your code zip format then how to include mvc in vs2012?
can you post them.

Author: Kapil10 Oct 2012 Member Level: Gold   Points : 1

Hi Jay,

I tried in past, its due to the size of project and lots of files in MVC the size is bigger then DNS support for now.

If you want i can send project to your email address. Let me know

Kapil

Guest Author: Kumr Aryan17 Mar 2013

Dear Kapil,
Send me the source code on my Email Address i.e kumar_aryan35@hotmail.com
Please..Please...Please

Thanks in Advance.

Guest Author: 14 Apr 2013

Hi,
I am interested to see the source code of this project. Have you uploaded it anywhere?
Thanks,

Author: DDK04 Mar 2014 Member Level: Silver   Points : 0

Hi Kapil,

Can you please send me this code on ashakulkarni2707@gmail.com mail id.

Author: Jayakumar.R10 Mar 2015 Member Level: Gold   Points : 0

hi
kapil

Send me the source code on my Email Address this kumaraspcode2009@gmail.com



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: