Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

Code First Approach in MVC using Entity Framework

Article:
Viewed:  1082 
Posted On:  4/14/2015 10:37:35 PM 
What is Code First Approach? How we can use Code First Approach in MVC? Step By Step Showing Code First Approach. 

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

1.png

Image 1.

2.png

Image 2.

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

 

3.png

Image 3.

4.png

Image 4.

5.png

Image 5.

6.png

Image 6.

Now Right Click On Model -> Add New Class

7.png

Image 7.

8.png

Image 8.

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

9.png

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

10.png

Image 10.

11.png

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.

12.png

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

13.png

Image 13.

14.png

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..

 

15.png

Image 15.

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

16.png

Image 16.

Now See your DB

17.png

Image 17.

Now Add More Records

18.png

Image 18.

Now Click on Edit

19.png

Image 19.

Now Click on Details.

20.png

Image 20.

Now Click on Delete.

21.png

Image 21.

  Comment:
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us