Code First Approach in MVC Using Entity Framework

Here with Entity Framework we can develop an application using any of the following 3 approaches.

  1. Code First
  2. Model First
  3. Database First
Now we will learn the Code First step-by-step. Open Visual Studio 2012 and go to "File" -> "New" -> "Project...".





Now right-click on the project in the Solution Explorer and select Manage NuGet Packages.









Now right-click on the Model and select Add New Class.





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


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace CodeFirstApproach.Models  
  7. {  
  8.     public class Student  
  9.     {  
  10.         public int ID { getset; }  
  11.         public string Name { getset; }  
  12.         public string Email { getset; }  
  13.         public string Class { getset; }  
  14.         public string Address { getset; }  
  15.         public string Mobile { getset; }  
  16.     }  
  17. }  
Now again right-click on the Model Folder and select Add New Class.




  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data.Entity;  
  6. using System.ComponentModel.DataAnnotations.Schema;  
  7.   
  8. namespace CodeFirstApproach.Models  
  9. {  
  10.     public class StudentContext:DbContext  
  11.     {  
  12.         public StudentContext(): base("name=DbConnectionString")  
  13.         {  
  14.         }   
  15.   
  16.         public DbSet<Student> Students { getset; }  
  17.   
  18.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  19.         {  
  20.             modelBuilder.Entity<Student>().HasKey(b => b.ID);  
  21.             modelBuilder.Entity<Student>().Property(b => b.ID)  
  22.                 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);              
  23.             base.OnModelCreating(modelBuilder);  
  24.         }  
  25.     }  
  26. }  
Here I am using a connection string. Be sure you define it in your web.config file.


  1. <add name="DbConnectionString"   
  2.          connectionString="Data Source=INDIA\MSSQLServer2k8;Initial Catalog=MyCodeFirstAPPDB;User ID=sa; Password=india;"   
  3.          providerName="System.Data.SqlClient" />  
Now we need to add a controller then right-click on the Controller Folder and select Add -> Controller.





Here in the Student Controller define an action method for Create/Read/Update/Delete as in the following.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using CodeFirstApproach.Models;  
  7.   
  8. namespace CodeFirstApproach.Controllers  
  9. {  
  10.     public class StudentController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /Student/  
  14.   
  15.         StudentContext objContext;  
  16.   
  17.         public StudentController()  
  18.         {  
  19.             objContext = new StudentContext();  
  20.         }   
  21.   
  22.         public ActionResult Index()  
  23.         {  
  24.             var students = objContext.Students.ToList();  
  25.             return View(students);  
  26.         }  
  27.   
  28.         public ViewResult Details(int id)  
  29.         {  
  30.             Student student = objContext.Students.Where(x => x.ID == id).SingleOrDefault();  
  31.             return View(student);  
  32.         }  
  33.  
  34.         #region Create Student  
  35.         public ActionResult Create()  
  36.         {  
  37.             return View(new Student());  
  38.         }  
  39.         [HttpPost]  
  40.         public ActionResult Create(Student student)  
  41.         {  
  42.             objContext.Students.Add(student);  
  43.             objContext.SaveChanges();  
  44.             return RedirectToAction("Index");  
  45.         }  
  46.         #endregion   
  47.  
  48.         #region Edit Student  
  49.         public ActionResult Edit(int id)  
  50.         {  
  51.             Student student = objContext.Students.Where(x => x.ID == id).SingleOrDefault();  
  52.             return View(student);  
  53.         }  
  54.         [HttpPost]  
  55.         public ActionResult Edit(Student model)  
  56.         {  
  57.             Student student = objContext.Students.Where(x => x.ID == model.ID).SingleOrDefault();  
  58.             if (student != null)  
  59.             {  
  60.                 objContext.Entry(student).CurrentValues.SetValues(model);  
  61.                 objContext.SaveChanges();  
  62.                 return RedirectToAction("Index");  
  63.             }  
  64.             return View(model);  
  65.         }  
  66.         #endregion   
  67.  
  68.         #region Delete Student  
  69.         public ActionResult Delete(int id)  
  70.         {  
  71.             Student student = objContext.Students.Find(id);  
  72.             return View(student);  
  73.         }  
  74.         [HttpPost]  
  75.         public ActionResult Delete(int id, Student Model)  
  76.         {  
  77.             var student = objContext.Students.Where(x => x.ID == id).SingleOrDefault();  
  78.             if (student != null)  
  79.             {  
  80.                 objContext.Students.Remove(student);  
  81.                 objContext.SaveChanges();  
  82.             }  
  83.             return RedirectToAction("Index");  
  84.         }  
  85.         #endregion  
  86.   
  87.     }  
  88. }  
Now My Views are: Index.cshtml
  1. @model IEnumerable<CodeFirstApproach.Models.Student>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. <p>  
  10.     @Html.ActionLink("Create New""Create")  
  11. </p>  
  12. <table>  
  13.     <tr>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.Name)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.Email)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.Class)  
  22.         </th>  
  23.         <th>  
  24.             @Html.DisplayNameFor(model => model.Address)  
  25.         </th>  
  26.         <th>  
  27.             @Html.DisplayNameFor(model => model.Mobile)  
  28.         </th>  
  29.         <th></th>  
  30.     </tr>  
  31.   
  32. @foreach (var item in Model) {  
  33.     <tr>  
  34.         <td>  
  35.             @Html.DisplayFor(modelItem => item.Name)  
  36.         </td>  
  37.         <td>  
  38.             @Html.DisplayFor(modelItem => item.Email)  
  39.         </td>  
  40.         <td>  
  41.             @Html.DisplayFor(modelItem => item.Class)  
  42.         </td>  
  43.         <td>  
  44.             @Html.DisplayFor(modelItem => item.Address)  
  45.         </td>  
  46.         <td>  
  47.             @Html.DisplayFor(modelItem => item.Mobile)  
  48.         </td>  
  49.         <td>  
  50.             @Html.ActionLink("Edit""Edit"new { id=item.ID }) |  
  51.             @Html.ActionLink("Details""Details"new { id=item.ID }) |  
  52.             @Html.ActionLink("Delete""Delete"new { id=item.ID })  
  53.         </td>  
  54.     </tr>  
  55. }  
  56.   
  57. </table>  
Create.cshtml
  1. @model CodeFirstApproach.Models.Student  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6.   
  7. <h2>Create</h2>  
  8.   
  9. @using (Html.BeginForm()) {  
  10.     @Html.ValidationSummary(true)  
  11.   
  12.     <fieldset>  
  13.         <legend>Student</legend>  
  14.   
  15.         <div class="editor-label">  
  16.             @Html.LabelFor(model => model.Name)  
  17.         </div>  
  18.         <div class="editor-field">  
  19.             @Html.EditorFor(model => model.Name)  
  20.             @Html.ValidationMessageFor(model => model.Name)  
  21.         </div>  
  22.   
  23.         <div class="editor-label">  
  24.             @Html.LabelFor(model => model.Email)  
  25.         </div>  
  26.         <div class="editor-field">  
  27.             @Html.EditorFor(model => model.Email)  
  28.             @Html.ValidationMessageFor(model => model.Email)  
  29.         </div>  
  30.   
  31.         <div class="editor-label">  
  32.             @Html.LabelFor(model => model.Class)  
  33.         </div>  
  34.         <div class="editor-field">  
  35.             @Html.EditorFor(model => model.Class)  
  36.             @Html.ValidationMessageFor(model => model.Class)  
  37.         </div>  
  38.   
  39.         <div class="editor-label">  
  40.             @Html.LabelFor(model => model.Address)  
  41.         </div>  
  42.         <div class="editor-field">  
  43.             @Html.EditorFor(model => model.Address)  
  44.             @Html.ValidationMessageFor(model => model.Address)  
  45.         </div>  
  46.   
  47.         <div class="editor-label">  
  48.             @Html.LabelFor(model => model.Mobile)  
  49.         </div>  
  50.         <div class="editor-field">  
  51.             @Html.EditorFor(model => model.Mobile)  
  52.             @Html.ValidationMessageFor(model => model.Mobile)  
  53.         </div>  
  54.   
  55.         <p>  
  56.             <input type="submit" value="Create" />  
  57.         </p>  
  58.     </fieldset>  
  59. }  
  60.   
  61. <div>  
  62.     @Html.ActionLink("Back to List""Index")  
  63. </div>  
  64.   
  65. @section Scripts {  
  66.     @Scripts.Render("~/bundles/jqueryval")  
  67. }  
Details.cshtml
  1. @model CodeFirstApproach.Models.Student  
  2.   
  3. @{  
  4.     ViewBag.Title = "Delete";  
  5. }  
  6.   
  7. <h2>Delete</h2>  
  8.   
  9. <h3>Are you sure you want to delete this?</h3>  
  10. <fieldset>  
  11.     <legend>Student</legend>  
  12.   
  13.     <div class="display-label">  
  14.          @Html.DisplayNameFor(model => model.Name)  
  15.     </div>  
  16.     <div class="display-field">  
  17.         @Html.DisplayFor(model => model.Name)  
  18.     </div>  
  19.   
  20.     <div class="display-label">  
  21.          @Html.DisplayNameFor(model => model.Email)  
  22.     </div>  
  23.     <div class="display-field">  
  24.         @Html.DisplayFor(model => model.Email)  
  25.     </div>  
  26.   
  27.     <div class="display-label">  
  28.          @Html.DisplayNameFor(model => model.Class)  
  29.     </div>  
  30.     <div class="display-field">  
  31.         @Html.DisplayFor(model => model.Class)  
  32.     </div>  
  33.   
  34.     <div class="display-label">  
  35.          @Html.DisplayNameFor(model => model.Address)  
  36.     </div>  
  37.     <div class="display-field">  
  38.         @Html.DisplayFor(model => model.Address)  
  39.     </div>  
  40.   
  41.     <div class="display-label">  
  42.          @Html.DisplayNameFor(model => model.Mobile)  
  43.     </div>  
  44.     <div class="display-field">  
  45.         @Html.DisplayFor(model => model.Mobile)  
  46.     </div>  
  47. </fieldset>  
  48. @using (Html.BeginForm()) {  
  49.     <p>  
  50.         <input type="submit" value="Delete" /> |  
  51.         @Html.ActionLink("Back to List""Index")  
  52.     </p>  
  53. }  
Edit.cshtml
  1. @model CodeFirstApproach.Models.Student  
  2.   
  3. @{  
  4.     ViewBag.Title = "Edit";  
  5. }  
  6.   
  7. <h2>Edit</h2>  
  8.   
  9. @using (Html.BeginForm()) {  
  10.     @Html.ValidationSummary(true)  
  11.   
  12.     <fieldset>  
  13.         <legend>Student</legend>  
  14.   
  15.         @Html.HiddenFor(model => model.ID)  
  16.   
  17.         <div class="editor-label">  
  18.             @Html.LabelFor(model => model.Name)  
  19.         </div>  
  20.         <div class="editor-field">  
  21.             @Html.EditorFor(model => model.Name)  
  22.             @Html.ValidationMessageFor(model => model.Name)  
  23.         </div>  
  24.   
  25.         <div class="editor-label">  
  26.             @Html.LabelFor(model => model.Email)  
  27.         </div>  
  28.         <div class="editor-field">  
  29.             @Html.EditorFor(model => model.Email)  
  30.             @Html.ValidationMessageFor(model => model.Email)  
  31.         </div>  
  32.   
  33.         <div class="editor-label">  
  34.             @Html.LabelFor(model => model.Class)  
  35.         </div>  
  36.         <div class="editor-field">  
  37.             @Html.EditorFor(model => model.Class)  
  38.             @Html.ValidationMessageFor(model => model.Class)  
  39.         </div>  
  40.   
  41.         <div class="editor-label">  
  42.             @Html.LabelFor(model => model.Address)  
  43.         </div>  
  44.         <div class="editor-field">  
  45.             @Html.EditorFor(model => model.Address)  
  46.             @Html.ValidationMessageFor(model => model.Address)  
  47.         </div>  
  48.   
  49.         <div class="editor-label">  
  50.             @Html.LabelFor(model => model.Mobile)  
  51.         </div>  
  52.         <div class="editor-field">  
  53.             @Html.EditorFor(model => model.Mobile)  
  54.             @Html.ValidationMessageFor(model => model.Mobile)  
  55.         </div>  
  56.   
  57.         <p>  
  58.             <input type="submit" value="Save" />  
  59.         </p>  
  60.     </fieldset>  
  61. }  
  62.   
  63. <div>  
  64.     @Html.ActionLink("Back to List""Index")  
  65. </div>  
  66.   
  67. @section Scripts {  
  68.     @Scripts.Render("~/bundles/jqueryval")  
  69. }  
Now run the app.



There is no database created so click on Create New.



Now see your DB as in the following:



Now add more records as in the following:



Now click on Edit.



Now click on Details.



Now click on Delete.

 


Similar Articles