In this article I am going to show how we can use Code
First Approach in MVC using Entity Framework. Basically Entity Framework is
ORM- Object Relation mapping. Here with Entity Framework we can develop
application with below 3 approaches.
Code First
Model First
Data Base First
Now we will learn Code First Step By Step
Open Visual Studio 2012 -> New -> Project

Image 1.

Image 2.
Now Right Click on Project Solution Explorer->
Manage NuGet Packages

Image 3.

Image 4.

Image 5.

Image 6.
Now Right Click On Model -> Add New Class

Image 7.

Image 8.
In your Class define property or column name which you
want in your SQL Server Table.

Image 9.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
namespace
CodeFirstApproach.Models
{
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Class { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
}
}
Now again
right click on Model Folder -> Add New Class

Image 10.

Image 11.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using
System.ComponentModel.DataAnnotations.Schema;
namespace
CodeFirstApproach.Models
{
public class StudentContext:DbContext
{
public StudentContext(): base("name=DbConnectionString")
{
}
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasKey(b
=> b.ID);
modelBuilder.Entity<Student>().Property(b
=> b.ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
base.OnModelCreating(modelBuilder);
}
}
}
Here I am
using a connection string. Make sure you define it in your web.config file.

Image 12.
<add name="DbConnectionString"
connectionString="Data
Source=INDIA\MSSQLServer2k8;Initial Catalog=MyCodeFirstAPPDB;User ID=sa;
Password=india;"
providerName="System.Data.SqlClient"
/>
Now We need to add a controller -> Right Click on Controller Folder
-> Add -> Controller

Image 13.

Image 14.
Here in Student
Controller Define action method for Create/Read/Update/Delete like below.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using
CodeFirstApproach.Models;
namespace
CodeFirstApproach.Controllers
{
public class StudentController : Controller
{
//
// GET: /Student/
StudentContext objContext;
public StudentController()
{
objContext = new StudentContext();
}
public ActionResult Index()
{
var students = objContext.Students.ToList();
return View(students);
}
public ViewResult Details(int id)
{
Student student=
objContext.Students.Where(x => x.ID == id).SingleOrDefault();
return View(student);
}
#region Create Student
public ActionResult Create()
{
return View(new Student());
}
[HttpPost]
public ActionResult Create(Student student)
{
objContext.Students.Add(student);
objContext.SaveChanges();
return RedirectToAction("Index");
}
#endregion
#region Edit Student
public ActionResult Edit(int id)
{
Student student =
objContext.Students.Where(x => x.ID == id).SingleOrDefault();
return View(student);
}
[HttpPost]
public ActionResult Edit(Student model)
{
Student student =
objContext.Students.Where(x => x.ID == model.ID).SingleOrDefault();
if (student != null)
{
objContext.Entry(student).CurrentValues.SetValues(model);
objContext.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
#endregion
#region Delete Student
public ActionResult Delete(int id)
{
Student student=
objContext.Students.Find(id);
return View(student);
}
[HttpPost]
public ActionResult Delete(int id, Student Model)
{
var student = objContext.Students.Where(x =>
x.ID == id).SingleOrDefault();
if (student != null)
{
objContext.Students.Remove(student);
objContext.SaveChanges();
}
return RedirectToAction("Index");
}
#endregion
}
}
Now My Views are: Index.cshtml
@model IEnumerable<CodeFirstApproach.Models.Student>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create
New",
"Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model =>
model.Name)
</th>
<th>
@Html.DisplayNameFor(model =>
model.Email)
</th>
<th>
@Html.DisplayNameFor(model =>
model.Class)
</th>
<th>
@Html.DisplayNameFor(model =>
model.Address)
</th>
<th>
@Html.DisplayNameFor(model =>
model.Mobile)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem =>
item.Name)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Email)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Class)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Address)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Mobile)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
Create.cshtml
@model CodeFirstApproach.Models.Student
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Student</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model =>
model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Class)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Class)
@Html.ValidationMessageFor(model =>
model.Class)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address)
@Html.ValidationMessageFor(model =>
model.Address)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Mobile)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Mobile)
@Html.ValidationMessageFor(model =>
model.Mobile)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to
List",
"Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Delete.cshtml
@model CodeFirstApproach.Models.Student
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you
want to delete this?</h3>
<fieldset>
<legend>Student</legend>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Name)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Email)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Email)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Class)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Class)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Address)
</div>
<div class="display-field">
@Html.DisplayFor(model =>
model.Address)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Mobile)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Mobile)
</div>
</fieldset>
@using (Html.BeginForm())
{
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to
List",
"Index")
</p>
}
Details.cshtml
@model CodeFirstApproach.Models.Student
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<fieldset>
<legend>Student</legend>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Name)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Email)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Email)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Class)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Class)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Address)
</div>
<div class="display-field">
@Html.DisplayFor(model =>
model.Address)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Mobile)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Mobile)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
@Html.ActionLink("Back to
List",
"Index")
</p>
Edit.cshtml
@model CodeFirstApproach.Models.Student
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Student</legend>
@Html.HiddenFor(model => model.ID)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model =>
model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model =>
model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Class)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Class)
@Html.ValidationMessageFor(model =>
model.Class)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address)
@Html.ValidationMessageFor(model =>
model.Address)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Mobile)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Mobile)
@Html.ValidationMessageFor(model =>
model.Mobile)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to
List",
"Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Now
Run the App..

Image 15.
There is no Data base
Created so click on Create New.

Image 16.
Now See your DB

Image 17.
Now Add More Records

Image 18.
Now Click on Edit

Image 19.
Now Click on Details.

Image 20.
Now Click on Delete.

Image 21.