Entity Framework Code First Approach With MVC

This scenario targets a database that doesn’t exist and code first will create, or an empty database that code first will add new tables .

Note: Make sure that the Entity Framework already installed with Visual Studio, otherwise install using NuGet Packages.

Step 1. Creating an MVC Application

  • Open Visual Studio
  • File, New, then click Project
  • Select ASP.NET MVC3/4 Web Application.
  • Enter the name of application as "CodeFirstDemo".
  • Click OK

Step 2. Creating the Model

Right click on the Models folder and create a model with the name of "User" as in the following image and create a property as in the below code,

solution

  1. public class User  
  2. {  
  3.     public int UserId  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string FirstName  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string LastName  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public string EMail  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23.     public string Address  
  24.     {  
  25.         get;  
  26.         set;  
  27.     }  
  28.     public string PhoneNo  
  29.     {  
  30.         get;  
  31.         set;  
  32.     }  
  33.     public string Company  
  34.     {  
  35.         get;  
  36.         set;  
  37.     }  
  38.     public string Designation  
  39.     {  
  40.         get;  
  41.         set;  
  42.     }  
  43. }  
Step 3. Create a DBContext

Create a class with the Name MVCDBContext as in the following screenshot and write the code as follows in MVCDBContext class.

solution

  1. using System.Data.Entity;  
  2. using System.Linq;  
  3. using CodeFirstDemo.Models;  
  4. namespace CodeFirstDemo  
  5. {  
  6.     public class MVCDBContext: DbContext  
  7.     {  
  8.         public DbSet < User > Users  
  9.         {  
  10.             get;  
  11.             set;  
  12.         }  
  13.     }  
  14. }  
[ Note : Make sure that you are using " System.Data.Entity " Namespace. ]

Step 4 : Create a Controller.

Right click on the Controller folder and create a controller with the name "MyController" as in the following image. Write the following code in Mycontroller.cs within Index Action.

solution

  1. public ActionResult Index()  
  2. {  
  3.     var dbContext = new MVCDBContext();  
  4.     var userList = from user in dbContext.Users select user;  
  5.     var users = new List < CodeFirstDemo.Models.User > ();  
  6.     if (userList.Any())  
  7.     {  
  8.         foreach(var user in userList)  
  9.         {  
  10.             users.Add(new CodeFirstDemo.Models.User()  
  11.             {  
  12.                 UserId = user.UserId, Address = user.Address,  
  13.                     Company = user.Company, FirstName = user.FirstName,  
  14.                     LastName = user.LastName, Designation = user.Designation,  
  15.                     EMail = user.EMail, PhoneNo = user.PhoneNo  
  16.             });  
  17.         }  
  18.     }  
  19.     ViewBag.FirstName = "My First Name";  
  20.     ViewData["FirstName"] = "My First Name";  
  21.     if (TempData.Any())  
  22.     {  
  23.         var tempData = TempData["TempData Name"];  
  24.     }  
  25.     return View(users);  
  26. }  
Now ,
  • Right click on Index and select Add View… as in the following screenshot.
  • Click on Add button that appear in the dialog box.

    View

  • Go to Views folder and choose Index.cshtml in My folder.

    solution

  • Type the following code in Index.cshtml file.
    1. @model List < CodeFirstDemo.Models.User > @  
    2. {  
    3.     ViewBag.Title = "Index";  
    4.     Layout = "~/Views/Shared/_Layout.cshtml";  
    5. }   
    6.   < h2 > Index   
    7.   < /h2>   
    8.   < p >   
    9.     @Html.ActionLink("Create New""Create")   
    10.   < /p>   
    11.   < div > < table > < tr > < th >   
    12.   FirstName   
    13.   < /th> < th >   
    14. LastName   
    15.   < /th> < th > EMail   
    16.   < /th> < th > Address   
    17.   < /th> < th > PhoneNo   
    18.   < /th> < th > Company   
    19.   < /th> < th > Designation   
    20.   < /th> < th > < /th> < /tr>  
    21. @foreach(var item in Model)  
    22. {   
    23.   < tr > < td >   
    24.     @Html.DisplayFor(modelItem => item.FirstName)   
    25.     < /td> < td > @Html.DisplayFor(modelItem => item.LastName)   
    26.       < /td> < td > @Html.DisplayFor(modelItem => item.EMail)   
    27.       < /td> < td > @Html.DisplayFor(modelItem => item.Address)   
    28.       < /td> < td > @Html.DisplayFor(modelItem => item.PhoneNo)   
    29.       < /td> < td > @Html.DisplayFor(modelItem => item.Company)   
    30.       < /td> < td > @Html.DisplayFor(modelItem => item.Designation)   
    31.       < /td> < td > @Html.ActionLink("Edit""Edit"new  
    32.     {  
    33.         id = item.UserId  
    34.     }) | @Html.ActionLink("Details""Details"new  
    35.     {  
    36.         id = item.UserId  
    37.     }) | @Html.ActionLink("Delete""Delete"new  
    38.     {  
    39.         id = item.UserId  
    40.     }) < /td> < /tr>  
    41. } < /table> < /div>  

    Now, again go to MyController and create a new action with the name of Details as follows.
    1. public ActionResult Details(int ? id)  
    2. {  
    3.     var dbContext = new MVCDBContext();  
    4.     var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);  
    5.     var user = new CodeFirstDemo.Models.User();  
    6.     if (userDetails != null)  
    7.     {  
    8.         user.UserId = userDetails.UserId;  
    9.         user.FirstName = userDetails.FirstName;  
    10.         user.LastName = userDetails.LastName;  
    11.         user.Address = userDetails.Address;  
    12.         user.PhoneNo = userDetails.PhoneNo;  
    13.         user.EMail = userDetails.EMail;  
    14.         user.Company = userDetails.Company;  
    15.         user.Designation = userDetails.Designation;  
    16.     }  
    17.     return View(user);  
    18. }  

    Again, Right click on the Details ActionResult and add view as same as index. Write the code as follows in your Details view which you just created.
    1. @model CodeFirstDemo.Models.User  
    2. @  
    3. {  
    4.     ViewBag.Title = "Details";  
    5. }   
    6. < h2 >   
    7.   Details   
    8. < /h2>   
    9.   < fieldset > < legend > User   
    10.   < /legend>   
    11.   < div class = "display-label" > FirstName   
    12.     < /div> < div class = "display-field" >  
    13.   @Html.DisplayFor(model => model.FirstName)   
    14.     < /div> < div class = "display-label" > LastName   
    15.     < /div> < div class = "display-field" >   
    16.   @Html.DisplayFor(model => model.LastName)   
    17.     < /div> < div class = "display-label" > EMail   
    18.     < /div> < div class = "display-field" >   
    19.   @Html.DisplayFor(model => model.EMail)   
    20.     < /div> < div class = "display-label" > Address   
    21.     < /div> < div class = "display-field" >   
    22.   @Html.DisplayFor(model => model.Address)   
    23.     < /div> < div class = "display-label" > PhoneNo   
    24.     < /div> < div class = "display-field" >   
    25.   @Html.DisplayFor(model => model.PhoneNo)   
    26.     < /div> < div class = "display-label" > Company   
    27.     < /div> < div class = "display-field" >   
    28.   @Html.DisplayFor(model => model.Company)   
    29.     < /div> < div class = "display-label" > Designation   
    30.     < /div> < div class = "display-field" >   
    31.   @Html.DisplayFor(model => model.Designation)   
    32.     < /div> < /fieldset> < p >   
    33.       @Html.ActionLink("Edit""Edit"new  
    34. {  
    35.     id = Model.UserId  
    36. }) | @Html.ActionLink("Back to List""Index") < /p>  

    Repeat the same process for creating an action in MyController for Create, Edit and Delete as follows and also add views.
    1. #region Edit...  
    2.     /// <summary>  
    3.     /// Get Action for Edit  
    4.     /// </summary>  
    5.     /// <param name="id"></param>  
    6.     /// <returns></returns>  
    7. public ActionResult Edit(int ? id)  
    8.     {  
    9.         var dbContext = new MVCDBContext();  
    10.         var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);  
    11.         var user = new CodeFirstDemo.Models.User();  
    12.         if (userDetails != null)  
    13.         {  
    14.             user.UserId = userDetails.UserId;  
    15.             user.FirstName = userDetails.FirstName;  
    16.             user.LastName = userDetails.LastName;  
    17.             user.Address = userDetails.Address;  
    18.             user.PhoneNo = userDetails.PhoneNo;  
    19.             user.EMail = userDetails.EMail;  
    20.             user.Company = userDetails.Company;  
    21.             user.Designation = userDetails.Designation;  
    22.         }  
    23.         return View(user);  
    24.     }  
    25.     /// <summary>  
    26.     /// Post Action for Edit  
    27.     /// </summary>  
    28.     /// <param name="id"></param>  
    29.     /// <param name="user"></param>  
    30.     /// <returns></returns>  
    31.     [HttpPost]  
    32. public ActionResult Edit(int ? id, User userDetails)  
    33. {  
    34.     TempData["TempData Name"] = "Akhil";  
    35.     try  
    36.     {  
    37.         var dbContext = new MVCDBContext();  
    38.         var user = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);  
    39.         if (user != null)  
    40.         {  
    41.             user.FirstName = userDetails.FirstName;  
    42.             user.LastName = userDetails.LastName;  
    43.             user.Address = userDetails.Address;  
    44.             user.PhoneNo = userDetails.PhoneNo;  
    45.             user.EMail = userDetails.EMail;  
    46.             user.Company = userDetails.Company;  
    47.             user.Designation = userDetails.Designation;  
    48.             dbContext.SaveChanges();  
    49.         }  
    50.         return RedirectToAction("Index");  
    51.     }  
    52.     catch  
    53.     {  
    54.         return View();  
    55.     }  
    56. }#  
    57. endregion# region Delete...  
    58.     /// <summary>  
    59.     /// Get Action for Delete  
    60.     /// </summary>  
    61.     /// <param name="id"></param>  
    62.     /// <returns></returns>  
    63. public ActionResult Delete(int ? id)  
    64.     {  
    65.         var dbContext = new MVCDBContext();  
    66.         var user = new CodeFirstDemo.Models.User();  
    67.         var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);  
    68.         if (userDetails != null)  
    69.         {  
    70.             user.FirstName = userDetails.FirstName;  
    71.             user.LastName = userDetails.LastName;  
    72.             user.Address = userDetails.Address;  
    73.             user.PhoneNo = userDetails.PhoneNo;  
    74.             user.EMail = userDetails.EMail;  
    75.             user.Company = userDetails.Company;  
    76.             user.Designation = userDetails.Designation;  
    77.         }  
    78.         return View(user);  
    79.     }  
    80.     /// <summary>  
    81.     /// Post Action for Delete  
    82.     /// </summary>  
    83.     /// <param name="id"></param>  
    84.     /// <param name="userDetails"> </param>  
    85.     /// <returns></returns>  
    86.     [HttpPost]  
    87. public ActionResult Delete(int ? id, CodeFirstDemo.Models.User userDetails)  
    88. {  
    89.     try  
    90.     {  
    91.         var dbContext = new MVCDBContext();  
    92.         var user = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);  
    93.         if (user != null)  
    94.         {  
    95.             dbContext.Users.Add(user);  
    96.             dbContext.SaveChanges();  
    97.         }  
    98.         return RedirectToAction("Index");  
    99.     }  
    100.     catch  
    101.     {  
    102.         return View();  
    103.     }  
    104. }#endregion  

Create.cshtml

  1. @model CodeFirstDemo.Models.User  
  2. @  
  3. {  
  4.     ViewBag.Title = "Create";  
  5. } < h2 > Create < /h2> < script src = "@Url.Content("~/Scripts/jquery.validate.min.js ")"  
  6. type = "text/javascript" > < /script> < script src = "@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js ")"  
  7. type = "text/javascript" > < /script>  
  8. @using(Html.BeginForm())  
  9. {  
  10.     @Html.ValidationSummary(true) < fieldset > < legend > User   
  11.       < /legend> < div class = "editor-label" >   
  12.     @Html.LabelFor(model => model.FirstName)   
  13.       < /div> < div class = "editor-field" >  
  14.     @Html.EditorFor(model => model.FirstName)  
  15.     @Html.ValidationMessageFor(model => model.FirstName)   
  16.       < /div> < div class = "editor-label" >   
  17.     @Html.LabelFor(model => model.LastName)   
  18.       < /div> < div class = "editor-field" >   
  19.     @Html.EditorFor(model => model.LastName)  
  20.     @Html.ValidationMessageFor(model => model.LastName)   
  21.       < /div> < div class = "editor-label" >   
  22.     @Html.LabelFor(model => model.EMail)   
  23.       < /div> < div class = "editor-field" >   
  24.     @Html.EditorFor(model => model.EMail)  
  25.     @Html.ValidationMessageFor(model => model.EMail)  
  26.       < /div> < div class = "editor-label" >   
  27.     @Html.LabelFor(model => model.Address)   
  28.       < /div> < div class = "editor-field" >   
  29.     @Html.EditorFor(model => model.Address)  
  30.     @Html.ValidationMessageFor(model => model.Address)   
  31.       < /div> < div class = "editor-label" >  
  32.     @Html.LabelFor(model => model.PhoneNo)   
  33.       < /div> < div class = "editor-field" >   
  34.     @Html.EditorFor(model => model.PhoneNo)  
  35.     @Html.ValidationMessageFor(model => model.PhoneNo)   
  36.       < /div> < div class = "editor-label" >   
  37.     @Html.LabelFor(model => model.Company)   
  38.       < /div> < div class = "editor-field" >   
  39.     @Html.EditorFor(model => model.Company)  
  40.     @Html.ValidationMessageFor(model => model.Company)   
  41.       < /div> < div class = "editor-label" >   
  42.     @Html.LabelFor(model => model.Designation)   
  43.       < /div> < div class = "editor-field" >   
  44.     @Html.EditorFor(model => model.Designation)  
  45.     @Html.ValidationMessageFor(model => model.Designation)   
  46.       < /div> < p > < input type = "submit"  
  47.     value = "Create" / > < /p> < /fieldset>  
  48. } < div > @Html.ActionLink("Back to List""Index")   
  49.   < /div>  
Delete.cshtml
  1. @model CodeFirstDemo.Models.User  
  2. @  
  3. {  
  4.     ViewBag.Title = "Delete";  
  5. }   
  6. < h2 > Delete   
  7.   < /h2>   
  8.   < h3 > Are you sure you want to delete this ?  
  9.     < /h3> < fieldset > < legend > User   
  10.     < /legend>   
  11.     < div class = "display-label" > FirstName   
  12.     < /div> < div class = "display-field" >   
  13.   @Html.DisplayFor(model => model.FirstName)   
  14.     < /div> < div class = "display-label" > LastName   
  15.     < /div> < div class = "display-field" >   
  16.   Html.DisplayFor(model => model.LastName)   
  17.     < /div> < div class = "display-label" > EMail  
  18.     < /div> < div class = "display-field" >  
  19.   @Html.DisplayFor(model => model.EMail)   
  20.     < /div> < div class = "display-label" > Address  
  21.     < /div> < div class = "display-field" >   
  22.   @Html.DisplayFor(model => model.Address)   
  23.     < /div> < div class = "display-label" > PhoneNo  
  24.     < /div> < div class = "display-field" >  
  25.   @Html.DisplayFor(model => model.PhoneNo)  
  26.     < /div> < div class = "display-label" > Company  
  27.     < /div> < div class = "display-field" >   
  28.   @Html.DisplayFor(model => model.Company)   
  29.     < /div> < div class = "display-label" > Designation  
  30.     < /div> < div class = "display-field" >   
  31.   @Html.DisplayFor(model => model.Designation)  
  32.     < /div> < /fieldset>  
  33. @using(Html.BeginForm())  
  34. < p > < input type = "submit"  
  35.     value = "Delete" / > | @Html.ActionLink("Back to List", "Index") < /p>  
  36. }  
Edit.cshtml
  1. @model CodeFirstDemo.Models.User  
  2. @  
  3. {  
  4.     ViewBag.Title = "Edit";  
  5. } < h2 > Edit < /h2> < script src = "@Url.Content("~/Scripts/jquery.validate.min.js ")"  
  6. type = "text/javascript" > < /script> < script src = "@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js ")"  
  7. type = "text/javascript" > < /script>  
  8. @using(Html.BeginForm())  
  9. {  
  10.     @Html.ValidationSummary(true) < fieldset > < legend > User < /legend>  
  11.     @Html.HiddenFor(model => model.UserId) < div class = "editor-label" > @Html.LabelFor(model => model.FirstName) < /div> < div class = "editor-field" > @Html.EditorFor(model => model.FirstName)  
  12.     @Html.ValidationMessageFor(model => model.FirstName)   
  13.       < /div> < div class = "editor-label" >   
  14.     @Html.LabelFor(model => model.LastName)   
  15.       < /div> < div class = "editor-field" >   
  16.     @Html.EditorFor(model => model.LastName)  
  17.     @Html.ValidationMessageFor(model => model.LastName)   
  18.       < /div> < div class = "editor-label" >   
  19.     @Html.LabelFor(model => model.EMail)   
  20.       < /div> < div class = "editor-field" >   
  21.     @Html.EditorFor(model => model.EMail)  
  22.     @Html.ValidationMessageFor(model => model.EMail)   
  23.       < /div> < div class = "editor-label" >   
  24.     @Html.LabelFor(model => model.Address)  
  25.       < /div> < div class = "editor-field" >   
  26.     @Html.EditorFor(model => model.Address)  
  27.     @Html.ValidationMessageFor(model => model.Address)  
  28.       < /div> < div class = "editor-label" >   
  29.     @Html.LabelFor(model => model.PhoneNo)   
  30.       < /div> < div class = "editor-field" >   
  31.     @Html.EditorFor(model => model.PhoneNo)  
  32.     @Html.ValidationMessageFor(model => model.PhoneNo)   
  33.       < /div> < div class = "editor-label" >   
  34.     @Html.LabelFor(model => model.Company)   
  35.       < /div> < div class = "editor-field" >  
  36.     @Html.EditorFor(model => model.Company)  
  37.     @Html.ValidationMessageFor(model => model.Company)   
  38.       < /div> < div class = "editor-label" >   
  39.     @Html.LabelFor(model => model.Designation)   
  40.       < /div> < div class = "editor-field" >   
  41.     @Html.EditorFor(model => model.Designation)  
  42.     @Html.ValidationMessageFor(model => model.Designation)   
  43.       < /div> < p > < input type = "submit"  
  44.     value = "Save" / > < /p> < /fieldset>  
  45.        
  46. } < div > @Html.ActionLink("Back to List""Index") < /div>  
Please make sure your Web.config file looks like the following:

config

Now press F5 to run the application,

Summary

In this walk-through we looked at code first development using a new database. We defined a model using classes and then used that model to create a database and performed CRUD operation.

Up Next
    Ebook Download
    View all
    Learn
    View all