Code First Approach in MVC With Entity Framework With Primary and Foreign Key Creation

In my previous article I explained what Code First Approach in MVC with Entity Framework is. Now in this article I will show how to create a Primary Key and Foreign Key using the code first approach in MVC with Entity Framework.

Here I will create 2 tables, Students and Course. Both tables will have a Primary Key and the Student table will reference the course table with CourseID as the Foreign Key.

Now open Visual Studio 2012 and select New Project.

mvc 4 web application

internet application

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

manage nuget package

Now here in this project I will create 2 tables, one is the Student table and the second one is the Course table. Both tables will have a Primary Key and the Student and Course tables will have a Foreign Key, CourseID. So here I will create 2 clasess in the Model Folder.

Student.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace CodeFirstApproachWithPrimaryForeignKey.Models  
  9. {  
  10.     public class Student  
  11.     {  
  12.         public Student()  
  13.         {  
  14.              
  15.         }  
  16.         [Key]  
  17.         public int Id { getset; }  
  18.         public string Name { getset; }  
  19.   
  20.         [DataType(DataType.Date),  
  21.          DisplayFormat(DataFormatString = "{0:dd/MM/yy}",  
  22.          ApplyFormatInEditMode = true)]  
  23.         public DateTime? DateOfBirth { getset; }  
  24.         public string EmailId { getset; }  
  25.         public string Address { getset; }  
  26.         public string City { getset; }  
  27.         public int CourseId { getset; }  
  28.   
  29.         public Course Course { getset; } // Navigation Property  
  30.   
  31.         [NotMapped]  
  32.         public string CourseName { getset; }  
  33.           
  34.     }  
  35. }  
Here CourseName will not be a field because I set it as NotMapped.
 
Now Course.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace CodeFirstApproachWithPrimaryForeignKey.Models  
  8. {  
  9.     public class Course  
  10.     {  
  11.         public Course()  
  12.         {  
  13.   
  14.         }  
  15.         [Key]  
  16.         public int CourseId { getset; }  
  17.         public string CourseName { getset; }  
  18.   
  19.         public List<Student> Students { getset; } // Navigation property  
  20.     }  
  21. }  
Now again right-click on the Model folder and add the new class StudentDBContext.cs.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations.Schema;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace CodeFirstApproachWithPrimaryForeignKey.Models  
  9. {  
  10.     public class StudentDBContext : DbContext  
  11.     {  
  12.         public StudentDBContext()  
  13.             : base("StudentDbContext")  
  14.         {  
  15.         }  
  16.   
  17.         public DbSet<Student> Students { getset; }  
  18.         public DbSet<Course> Courses { getset; }  
  19.   
  20.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  21.         {  
  22.             modelBuilder.Entity<Course>().HasKey(p => p.CourseId);  
  23.             modelBuilder.Entity<Course>().Property(c => c.CourseId)  
  24.                 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);  
  25.   
  26.             modelBuilder.Entity<Student>().HasKey(b => b.Id);  
  27.             modelBuilder.Entity<Student>().Property(b => b.Id)  
  28.                 .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);  
  29.   
  30.             modelBuilder.Entity<Student>().HasRequired(p => p.Course)  
  31.                 .WithMany(b => b.Students).HasForeignKey(b => b.CourseId);  
  32.   
  33.             base.OnModelCreating(modelBuilder);  
  34.         }  
  35.     }  
  36. }  

Here In this StudentDBContext.cs you can see I am using OnModelCreating. Here I define what will be the Primary Key and what will be the Foreign Key.

Now right-click on Controller then select Add -> Controller -> Student.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using CodeFirstApproachWithPrimaryForeignKey.Models;  
  7.   
  8. namespace CodeFirstApproachWithPrimaryForeignKey.Controllers  
  9. {  
  10.     public class StudentController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /Student/  
  14.   
  15.         StudentDBContext objContext;  
  16.   
  17.         public StudentController()  
  18.         {  
  19.             objContext = new StudentDBContext();  
  20.         }  
  21.  
  22.         #region List and Details student  
  23.   
  24.         public ActionResult Index()  
  25.         {  
  26.             var students = (from p in objContext.Students  
  27.                             join f in objContext.Courses  
  28.                         on p.CourseId equals f.CourseId  
  29.                             select new  
  30.                             {  
  31.                                 Id = p.Id,  
  32.                                 Name = p.Name,  
  33.                                 DateOfBirth = p.DateOfBirth,  
  34.                                 EmailId = p.EmailId,  
  35.                                 Address = p.Address,  
  36.                                 City = p.City,  
  37.                                 CourseName = f.CourseName  
  38.                             }).ToList()  
  39.                       .Select(x => new Student()  
  40.                       {  
  41.                           Id = x.Id,  
  42.                           Name = x.Name,  
  43.                           DateOfBirth = x.DateOfBirth,  
  44.                           EmailId = x.EmailId,  
  45.                           Address = x.Address,  
  46.                           City = x.City,  
  47.                           CourseName = x.CourseName  
  48.                       });  
  49.             return View(students.ToList());  
  50.         }  
  51.   
  52.         public ViewResult Details(int id)  
  53.         {  
  54.             //Student student = objContext.Students.Where(x => x.Id == id).SingleOrDefault();  
  55.             var student = (from p in objContext.Students  
  56.                             join f in objContext.Courses  
  57.                         on p.CourseId equals f.CourseId  
  58.                         where (p.Id==id)  
  59.                             select new  
  60.                             {  
  61.                                 Id = p.Id,  
  62.                                 Name = p.Name,  
  63.                                 DateOfBirth = p.DateOfBirth,  
  64.                                 EmailId = p.EmailId,  
  65.                                 Address = p.Address,  
  66.                                 City = p.City,  
  67.                                 CourseName = f.CourseName  
  68.                             }).ToList()  
  69.                      .Select(x => new Student()  
  70.                      {  
  71.                          Id = x.Id,  
  72.                          Name = x.Name,  
  73.                          DateOfBirth = x.DateOfBirth,  
  74.                          EmailId = x.EmailId,  
  75.                          Address = x.Address,  
  76.                          City = x.City,  
  77.                          CourseName = x.CourseName  
  78.                      }).SingleOrDefault();  
  79.             return View(student);  
  80.         }  
  81.  
  82.         #endregion  
  83.  
  84.         #region Create student  
  85.   
  86.         public ActionResult Create()  
  87.         {  
  88.             var data = from p in objContext.Courses  
  89.                        select new  
  90.                        {  
  91.                            CourseID = p.CourseId,  
  92.                            CourseName = p.CourseName  
  93.                        };  
  94.   
  95.             SelectList list = new SelectList(data, "CourseID""CourseName");  
  96.             ViewBag.Roles = list;  
  97.   
  98.             return View(new Student());  
  99.         }  
  100.   
  101.         [HttpPost]  
  102.         public ActionResult Create(Student student)  
  103.         {  
  104.             objContext.Students.Add(student);  
  105.             objContext.SaveChanges();  
  106.             return RedirectToAction("Index");  
  107.         }  
  108.  
  109.         #endregion  
  110.  
  111.         #region Edit student  
  112.   
  113.         public ActionResult Edit(int id)  
  114.         {  
  115.             var data = from p in objContext.Courses  
  116.                        select new  
  117.                        {  
  118.                            CourseID = p.CourseId,  
  119.                            CourseName = p.CourseName  
  120.                        };  
  121.   
  122.             SelectList list = new SelectList(data, "CourseID""CourseName");  
  123.             ViewBag.Roles = list;  
  124.   
  125.             Student student = objContext.Students.Where(x => x.Id == id).SingleOrDefault();  
  126.             return View(student);  
  127.         }  
  128.   
  129.   
  130.         [HttpPost]  
  131.         public ActionResult Edit(Student model)  
  132.         {  
  133.             Student student = objContext.Students.Where(x => x.Id == model.Id).SingleOrDefault();  
  134.             if (student != null)  
  135.             {  
  136.                 objContext.Entry(student).CurrentValues.SetValues(model);  
  137.                 objContext.SaveChanges();  
  138.                 return RedirectToAction("Index");  
  139.             }  
  140.   
  141.             return View(model);  
  142.         }  
  143.  
  144.         #endregion  
  145.  
  146.         #region Delete student  
  147.   
  148.         public ActionResult Delete(int id)  
  149.         {  
  150.             Student student = objContext.Students.Find(id);  
  151.             return View(student);  
  152.         }  
  153.   
  154.         [HttpPost]  
  155.         public ActionResult Delete(int id, Student model)  
  156.         {  
  157.             var student = objContext.Students.Where(x => x.Id == id).SingleOrDefault();  
  158.             if (student != null)  
  159.             {  
  160.                 objContext.Students.Remove(student);  
  161.                 objContext.SaveChanges();  
  162.             }  
  163.             return RedirectToAction("Index");  
  164.         }  
  165.         #endregion  
  166.     }  
  167. }  
Views Are for Create/Read/Details/Edit/Delete
 
Index.cshtml
  1. <h2>Showing All Students</h2>  
  2.   
  3. <p>  
  4.     @Html.ActionLink("Create New", "Create")  
  5. </p>  
  6. <table style="width:100%;">  
  7.    <tr>  
  8.         <th >  
  9.             @Html.DisplayNameFor(model => model.Name)  
  10.         </th>  
  11.        <th style="width:20%;">  
  12.             @Html.DisplayNameFor(model => model.DateOfBirth)  
  13.         </th>  
  14.         <th style="width:20%;">  
  15.             @Html.DisplayNameFor(model => model.EmailId)  
  16.         </th>  
  17.        <th>  
  18.             @Html.DisplayNameFor(model => model.Address)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.City)  
  22.         </th>  
  23.       <th>  
  24.             @Html.DisplayNameFor(model => model.CourseName)  
  25.         </th>  
  26.         <th></th>  
  27.     </tr>  
  28.   
  29. @foreach (var item in Model) {  
  30.     <tr>  
  31.         <td>  
  32.             @Html.DisplayFor(modelItem => item.Name)  
  33.         </td>  
  34.         <td>  
  35.             @Html.DisplayFor(modelItem => item.DateOfBirth)  
  36.         </td>  
  37.         <td>  
  38.             @Html.DisplayFor(modelItem => item.EmailId)  
  39.         </td>  
  40.         <td>  
  41.             @Html.DisplayFor(modelItem => item.Address)  
  42.         </td>  
  43.         <td>  
  44.             @Html.DisplayFor(modelItem => item.City)  
  45.         </td>  
  46.         <td>  
  47.             @Html.DisplayFor(modelItem => item.CourseName)  
  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 CodeFirstApproachWithPrimaryForeignKey.Models.Student  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6.   
  7. <h2>Create</h2>  
  8.   
  9. @using (Html.BeginForm())  
  10. {  
  11.     @Html.ValidationSummary(true)  
  12.   
  13.     <fieldset>  
  14.         <legend>Student</legend>  
  15.   
  16.         <div class="editor-label">  
  17.             @Html.LabelFor(model => model.Name)  
  18.         </div>  
  19.         <div class="editor-field">  
  20.             @Html.EditorFor(model => model.Name)  
  21.             @Html.ValidationMessageFor(model => model.Name)  
  22.         </div>  
  23.   
  24.         <div class="editor-label">  
  25.             @Html.LabelFor(model => model.DateOfBirth)  
  26.         </div>  
  27.         <div class="editor-field">  
  28.             @Html.EditorFor(model => model.DateOfBirth)  
  29.             @Html.ValidationMessageFor(model => model.DateOfBirth)  
  30.         </div>  
  31.   
  32.         <div class="editor-label">  
  33.             @Html.LabelFor(model => model.EmailId)  
  34.         </div>  
  35.         <div class="editor-field">  
  36.             @Html.EditorFor(model => model.EmailId)  
  37.             @Html.ValidationMessageFor(model => model.EmailId)  
  38.         </div>  
  39.   
  40.         <div class="editor-label">  
  41.             @Html.LabelFor(model => model.Address)  
  42.         </div>  
  43.         <div class="editor-field">  
  44.             @Html.EditorFor(model => model.Address)  
  45.             @Html.ValidationMessageFor(model => model.Address)  
  46.         </div>  
  47.   
  48.         <div class="editor-label">  
  49.             @Html.LabelFor(model => model.City)  
  50.         </div>  
  51.         <div class="editor-field">  
  52.             @Html.EditorFor(model => model.City)  
  53.             @Html.ValidationMessageFor(model => model.City)  
  54.         </div>  
  55.   
  56.         <div class="editor-label">  
  57.             @Html.LabelFor(model => model.CourseId)  
  58.         </div>  
  59.         <div class="editor-field">  
  60.             @Html.DropDownListFor(m=>m.CourseId, ViewBag.Roles as SelectList, "Select ...", new { @class = "myClass"style = "width: 250px;" })  
  61.   
  62.            @* @Html.EditorFor(model => model.CourseId)*@  
  63.             @Html.ValidationMessageFor(model => model.CourseId)  
  64.         </div>  
  65.          
  66.         <p>  
  67.             <input type="submit" value="Create" />  
  68.         </p>  
  69.     </fieldset>  
  70. }  
  71.   
  72. <div>  
  73.     @Html.ActionLink("Back to List", "Index")  
  74. </div>  
  75.   
  76. @section Scripts {  
  77.     @Scripts.Render("~/bundles/jqueryval")  
  78. }  
Delete.cshtml
  1. @model CodeFirstApproachWithPrimaryForeignKey.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. <table>  
  11.     <tr>  
  12.         <td>@Html.DisplayNameFor(model => model.Name)</td>  
  13.         <td>@Html.DisplayFor(model => model.Name)</td>  
  14.     </tr>  
  15.     <tr>  
  16.         <td>@Html.DisplayNameFor(model => model.DateOfBirth)</td>  
  17.         <td>@Html.DisplayFor(model => model.DateOfBirth)</td>  
  18.     </tr>  
  19.     <tr>  
  20.         <td>@Html.DisplayNameFor(model => model.EmailId)</td>  
  21.         <td>@Html.DisplayFor(model => model.EmailId)</td>  
  22.     </tr>  
  23.     <tr>  
  24.         <td>@Html.DisplayNameFor(model => model.Address)</td>  
  25.         <td>@Html.DisplayFor(model => model.Address)</td>  
  26.     </tr>  
  27.     <tr>  
  28.         <td>@Html.DisplayNameFor(model => model.City)</td>  
  29.         <td>@Html.DisplayFor(model => model.City)</td>  
  30.     </tr>  
  31.     <tr>  
  32.         <td>@Html.DisplayNameFor(model => model.CourseName)</td>  
  33.         <td>@Html.DisplayFor(model => model.CourseName)</td>  
  34.     </tr>  
  35.   
  36.     <tr style="background-color: orange; padding: 25px;">  
  37.         <td></td>  
  38.         <td>@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |  
  39.     @Html.ActionLink("Back to List", "Index")</td>  
  40.   
  41.     </tr>  
  42. </table>  
  43.   
  44. @using (Html.BeginForm())  
  45. {  
  46.     <table>  
  47.         <tr style="background-color: orange; padding: 25px;">  
  48.             <td></td>  
  49.             <td>  
  50.                 <input type="submit" value="Delete" />  
  51.   
  52.                 @Html.ActionLink("Back to List", "Index")  
  53.             </td>  
  54.   
  55.         </tr>  
  56.     </table>   
  57. }  
Details.cshtml
  1. @model CodeFirstApproachWithPrimaryForeignKey.Models.Student  
  2.   
  3. @{  
  4.     ViewBag.Title = "Details";  
  5. }  
  6.   
  7. <h2>Details Of Student</h2>  
  8.    
  9.   
  10. <table>  
  11.     <tr>  
  12.         <td>@Html.DisplayNameFor(model => model.Name)</td>  
  13.         <td>@Html.DisplayFor(model => model.Name)</td>  
  14.     </tr>  
  15.     <tr>  
  16.         <td>@Html.DisplayNameFor(model => model.DateOfBirth)</td>  
  17.         <td>@Html.DisplayFor(model => model.DateOfBirth)</td>  
  18.     </tr>  
  19.     <tr>  
  20.         <td>@Html.DisplayNameFor(model => model.EmailId)</td>  
  21.         <td>@Html.DisplayFor(model => model.EmailId)</td>  
  22.     </tr>  
  23.     <tr>  
  24.         <td>@Html.DisplayNameFor(model => model.Address)</td>  
  25.         <td>@Html.DisplayFor(model => model.Address)</td>  
  26.     </tr>  
  27.     <tr>  
  28.         <td>@Html.DisplayNameFor(model => model.City)</td>  
  29.         <td>@Html.DisplayFor(model => model.City)</td>  
  30.     </tr>  
  31.     <tr>  
  32.         <td>@Html.DisplayNameFor(model => model.CourseName)</td>  
  33.         <td>@Html.DisplayFor(model => model.CourseName)</td>  
  34.     </tr>  
  35.       
  36.     <tr style="background-color: orange; padding: 25px;">  
  37.         <td></td>  
  38.         <td>@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |  
  39.     @Html.ActionLink("Back to List", "Index")</td>  
  40.    
  41.     </tr>  
  42. </table>  
Edit.cshtml
  1. @model CodeFirstApproachWithPrimaryForeignKey.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.DateOfBirth)  
  27.         </div>  
  28.         <div class="editor-field">  
  29.             @Html.EditorFor(model => model.DateOfBirth)  
  30.             @Html.ValidationMessageFor(model => model.DateOfBirth)  
  31.         </div>  
  32.   
  33.         <div class="editor-label">  
  34.             @Html.LabelFor(model => model.EmailId)  
  35.         </div>  
  36.         <div class="editor-field">  
  37.             @Html.EditorFor(model => model.EmailId)  
  38.             @Html.ValidationMessageFor(model => model.EmailId)  
  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.City)  
  51.         </div>  
  52.         <div class="editor-field">  
  53.             @Html.EditorFor(model => model.City)  
  54.             @Html.ValidationMessageFor(model => model.City)  
  55.         </div>  
  56.   
  57.         <div class="editor-label">  
  58.             @Html.LabelFor(model => model.CourseId)  
  59.         </div>  
  60.         <div class="editor-field">  
  61.              @Html.DropDownListFor(m=>m.CourseId, ViewBag.Roles as SelectList, "Select ...", new { @class = "myClass"style = "width: 250px;" })  
  62.   
  63.            @* @Html.EditorFor(model => model.CourseId)*@  
  64.             @Html.ValidationMessageFor(model => model.CourseId)  
  65.         </div>  
  66.   
  67.         <p>  
  68.             <input type="submit" value="Save" />  
  69.         </p>  
  70.     </fieldset>  
  71. }  
  72.   
  73. <div>  
  74.     @Html.ActionLink("Back to List", "Index")  
  75. </div>  
  76.   
  77. @section Scripts {  
  78.     @Scripts.Render("~/bundles/jqueryval")  
  79. }  
Now again right-click on Controller then select Add-> Controller -> Course.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using CodeFirstApproachWithPrimaryForeignKey.Models;  
  7.   
  8. namespace CodeFirstApproachWithPrimaryForeignKey.Controllers  
  9. {  
  10.     public class CourseController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /Course/  
  14.   
  15.         StudentDBContext objContext;  
  16.         public CourseController()  
  17.         {  
  18.             objContext = new StudentDBContext();  
  19.         }  
  20.  
  21.         #region List and Details course  
  22.   
  23.         public ActionResult Index()  
  24.         {  
  25.             var courses = objContext.Courses.ToList();  
  26.             return View(courses);  
  27.         }  
  28.   
  29.         public ViewResult Details(int id)  
  30.         {  
  31.             Course course = objContext.Courses.Where(x => x.CourseId == id).SingleOrDefault();  
  32.             return View(course);  
  33.         }  
  34.  
  35.         #endregion  
  36.  
  37.         #region Create course  
  38.   
  39.         public ActionResult Create()  
  40.         {  
  41.             return View(new Course());  
  42.         }  
  43.   
  44.         [HttpPost]  
  45.         public ActionResult Create(Course course)  
  46.         {  
  47.             objContext.Courses.Add(course);  
  48.             objContext.SaveChanges();  
  49.             return RedirectToAction("Index");  
  50.         }  
  51.  
  52.         #endregion  
  53.  
  54.         #region edit course  
  55.   
  56.         public ActionResult Edit(int id)  
  57.         {  
  58.             Course course = objContext.Courses.Where(x => x.CourseId == id).SingleOrDefault();  
  59.             return View(course);  
  60.         }  
  61.   
  62.   
  63.         [HttpPost]  
  64.         public ActionResult Edit(Course model)  
  65.         {  
  66.             Course course = objContext.Courses.Where(x => x.CourseId == model.CourseId).SingleOrDefault();  
  67.             if (course != null)  
  68.             {  
  69.                 objContext.Entry(course).CurrentValues.SetValues(model);  
  70.                 objContext.SaveChanges();  
  71.                 return RedirectToAction("Index");  
  72.             }  
  73.                 
  74.             return View(model);  
  75.         }  
  76.  
  77.       #endregion  
  78.  
  79.         #region Delete course  
  80.         public ActionResult Delete(int id)  
  81.         {  
  82.             Course course = objContext.Courses.Find(id);  
  83.             return View(course);  
  84.         }  
  85.   
  86.         [HttpPost]  
  87.         public ActionResult Delete(int id, Course model)  
  88.         {  
  89.             var course = objContext.Courses.Where(x => x.CourseId == id).SingleOrDefault();  
  90.             if (course != null)  
  91.             {  
  92.                 objContext.Courses.Remove(course);  
  93.                 objContext.SaveChanges();  
  94.             }  
  95.             return RedirectToAction("Index");  
  96.         }  
  97.         #endregion  
  98.   
  99.     }  
  100. }  
View for Course

Index.cshtml
  1. @model IEnumerable<CodeFirstApproachWithPrimaryForeignKey.Models.Course>  
  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.CourseName)  
  16.         </th>  
  17.         <th></th>  
  18.     </tr>  
  19.   
  20. @foreach (var item in Model) {  
  21.     <tr>  
  22.         <td>  
  23.             @Html.DisplayFor(modelItem => item.CourseName)  
  24.         </td>  
  25.         <td>  
  26.             @Html.ActionLink("Edit", "Edit", new { id=item.CourseId }) |  
  27.             @Html.ActionLink("Details", "Details", new { id=item.CourseId }) |  
  28.             @Html.ActionLink("Delete", "Delete", new { id=item.CourseId })  
  29.         </td>  
  30.     </tr>  
  31. }  
  32.   
  33. </table>  
Create.cshtml
  1. @model CodeFirstApproachWithPrimaryForeignKey.Models.Course  
  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>Course</legend>  
  14.   
  15.         <div class="editor-label">  
  16.             @Html.LabelFor(model => model.CourseName)  
  17.         </div>  
  18.         <div class="editor-field">  
  19.             @Html.EditorFor(model => model.CourseName)  
  20.             @Html.ValidationMessageFor(model => model.CourseName)  
  21.         </div>  
  22.   
  23.         <p>  
  24.             <input type="submit" value="Create" />  
  25.         </p>  
  26.     </fieldset>  
  27. }  
  28.   
  29. <div>  
  30.     @Html.ActionLink("Back to List", "Index")  
  31. </div>  
  32.   
  33. @section Scripts {  
  34.     @Scripts.Render("~/bundles/jqueryval")  
  35. }  
Delete.cshtml
  1. model CodeFirstApproachWithPrimaryForeignKey.Models.Course  
  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>Course</legend>  
  12.   
  13.     <div class="display-label">  
  14.          @Html.DisplayNameFor(model => model.CourseName)  
  15.     </div>  
  16.     <div class="display-field">  
  17.         @Html.DisplayFor(model => model.CourseName)  
  18.     </div>  
  19. </fieldset>  
  20. @using (Html.BeginForm()) {  
  21.     <p>  
  22.         <input type="submit" value="Delete" /> |  
  23.         @Html.ActionLink("Back to List", "Index")  
  24.     </p>  
  25. }  
Details.cshtml
  1. @model CodeFirstApproachWithPrimaryForeignKey.Models.Course  
  2.   
  3. @{  
  4.     ViewBag.Title = "Details";  
  5. }  
  6.   
  7. <h2>Details</h2>  
  8.   
  9. <fieldset>  
  10.     <legend>Course</legend>  
  11.   
  12.     <div class="display-label">  
  13.          @Html.DisplayNameFor(model => model.CourseName)  
  14.     </div>  
  15.     <div class="display-field">  
  16.         @Html.DisplayFor(model => model.CourseName)  
  17.     </div>  
  18. </fieldset>  
  19. <p>  
  20.     @Html.ActionLink("Edit", "Edit", new { id=Model.CourseId }) |  
  21.     @Html.ActionLink("Back to List", "Index")  
  22. </p>  
Edit.cshtml
  1. @model CodeFirstApproachWithPrimaryForeignKey.Models.Course  
  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>Course</legend>  
  14.   
  15.         @Html.HiddenFor(model => model.CourseId)  
  16.   
  17.         <div class="editor-label">  
  18.             @Html.LabelFor(model => model.CourseName)  
  19.         </div>  
  20.         <div class="editor-field">  
  21.             @Html.EditorFor(model => model.CourseName)  
  22.             @Html.ValidationMessageFor(model => model.CourseName)  
  23.         </div>  
  24.   
  25.         <p>  
  26.             <input type="submit" value="Save" />  
  27.         </p>  
  28.     </fieldset>  
  29. }  
  30.   
  31. <div>  
  32.     @Html.ActionLink("Back to List", "Index")  
  33. </div>  
  34.   
  35. @section Scripts {  
  36.     @Scripts.Render("~/bundles/jqueryval")  
  37. }  
Run the Application

create

Now see your database:

database

Click on Course then select Create New.

create new

Showing All Course List:

course list

Click on Edit Course:

edit course

Details of a course:

course detail

Delete an existing Course:

delete course

Now click on Student-> Create New.

student create new

List of all students.

student list

Edit any student record:

edit student

Details of any student:

student detail

Delete any student record:

delete student

Now see your database. See the records in both tables and see the Primary Key and Foreign Key existence:

check database

If you want to run this application in your machine then just change the connection string in the web.config file.

Up Next
    Ebook Download
    View all
    Learn
    View all