ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach

Introduction 

In this article, we will discuss the Code-First Approach in Entity Framework Core using ASP.NET Core 2.1. Entity Framework Core is the new technology introduced by Microsoft along with the introduction of ASP.NET Core. As per Microsoft, ASP.NETsp.Net Core is the next generation of the Asp.Net technology. In the earlier version of Asp.Net; i.e. Asp.Net 3.5, we normally used the ADO.Net to communicate with the SQL based database for storing data or fetching the data. In this process, we normally used the dataset object to retrieve the data from the database and then we converted the dataset objects to the .Net or C# class objects or vice-versa to implement the business logic. Ultimately it is not a short process and there is a high chance of making a mistake in this process.

So, in 2008, Microsoft first introduced a technology called Entity Framework along with Asp.Net 3.5 Service Pack1 which basically automates the entire process of database connection and data retrieval steps. But in spite of that release, Entity Framework became the main topic of discussion in 2011 when Microsoft introduced Entity Framework along with the Code First Approach in the Asp.Net 4.1 version. The code first approach is mainly useful when we follow the Domain Driven Design or Development. In the process, we mainly focus on the domain structure of the application and start creating the classes or models for our domain entity rather than designing the database or its tables first. The entity classes or models which we create for designing the domain application will be mapped with the table objects of the database. The below image demonstrates the code first approach.

ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach
So, the above image shows that Entity Framework API will create the database or tables on the basis of the defined domain or model classes. So, in the Code First Approach, we always need to start the coding using C# in the case of Asp.Net. So, in the case of Code First Approach, we need to follow the below steps sequentially,
  1. Create or Modify the Entity Class
  2. Configure these class using Data Annotations or Fluent API
  3. Create the Database or Tables using Migration Command
  4. Design the Views on the basis of Model Class

Below the diagrams demonstrate the workflow of the Code First Approach. 

ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach

So, in the Asp.net Core or Entity Framework Core, we can also perform the same code first approach for developing our applications. Basically, Entity Framework or Entity Framework core is an Open Source based Framework which totally depends on the Object Relational Mapping or ORM Model. This framework basically reduced the developer’s effort for establishing the database connection or save data to the database or retrieve data from the database. So, in this article, we will discuss how we can create a CRUD based operation in Asp.Net Core using Entity Framework Core in Code First Approach.

Perquisite
  1. Visual Studio 2017 (Any Edition – Community / Professional / Enterprise)
  2. Microsoft SQL Server 2008 or above.
  3. .Net Core 2.1 SDK or Later Version
Steps to Create Model Class
 
Step 1
 
Now, we first want to create the domain classes for the Applications. So, we open the Visual Studio 2017 and Create a Blank Solution as below,
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach

Step 2

Now, a .Net Class Library Project in this Blank Solution for creating our Model Class in Solutions.
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 

Step 3

Now, we need to install the Entity Framework Related Packages in this .Net Class Library Project. For that open the Nuget Package Manager from Tools Menu and Install the Below Packages using Nuget Package Manager.
  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.SqlServer
  3. Microsoft.EntityFrameworkCore.Tools
These three packages are responsible for creating the migration script as per the entity models and creating objects in the database & tables.
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 

Step 4

Now, create two classes named Department and Designation, which are our model classes as below,
 
Department.cs
  1. using System.ComponentModel.DataAnnotations;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4. namespace DataContextLayer.Models  
  5. {  
  6.     public class Department  
  7.     {  
  8.         public int DepartmentId { getset; }  
  9.   
  10.         public string DepartmentCode { getset; }  
  11.   
  12.         public string DepartmentName { getset; }  
  13.   
  14.         public string Description { getset; }  
  15.     }  
  16. }  
Designation.cs
  1. using System.ComponentModel.DataAnnotations;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4. namespace DataContextLayer.Models  
  5. {  
  6.     public class Designation  
  7.     {  
  8.         public int DesignationId { getset; }  
  9.   
  10.         public string DesignationCode { getset; }  
  11.   
  12.         public string DesignationName { getset; }  
  13.   
  14.         public int DepartmentId { getset; }  
  15.   
  16.         public string DepartmentName { getset; }  
  17.           
  18.     }  
  19. }  
Steps to Apply Data Annotations

Step 1

Now, the classes which we create above are independent and do not have any relation between them. So, first we apply the data annotation in the department class as below.
  1. using System.ComponentModel.DataAnnotations;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4. namespace DataContextLayer.Models  
  5. {  
  6.     [Table("Department", Schema = "dbo")]  
  7.     public class Department  
  8.     {  
  9.         [Key]  
  10.         [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  11.         [Display(Name = "Department Id")]  
  12.         public int DepartmentId { getset; }  
  13.   
  14.         [Required]  
  15.         [Column(TypeName = "varchar(20)")]  
  16.         [Display(Name = "Department Code")]  
  17.         public string DepartmentCode { getset; }  
  18.   
  19.         [Required]  
  20.         [Column(TypeName = "varchar(100)")]  
  21.         [Display(Name = "Department Description")]  
  22.         public string DepartmentName { getset; }  
  23.   
  24.         [Column(TypeName = "varchar(100)")]  
  25.         public string Description { getset; }  
  26.     }  
  27. }  

Step 2

Now, we will apply the data annotations in the designation class also. In the Designation class, we have an attribute called DepartmentId which needs to be implemented as a Foreign key in the Database Tables concept. That’s why we implement the Foreign Key annotation in the Designation class as below.
  1. using System.ComponentModel.DataAnnotations;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4. namespace DataContextLayer.Models  
  5. {  
  6.     [Table("Designation", Schema = "dbo")]  
  7.     public class Designation  
  8.     {  
  9.         [Key]  
  10.         [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  11.         public int DesignationId { getset; }  
  12.   
  13.         [Required]  
  14.         [Column(TypeName = "varchar(20)")]  
  15.         [Display(Name = "Designation Code")]  
  16.         public string DesignationCode { getset; }  
  17.   
  18.         [Required]  
  19.         [Column(TypeName = "varchar(100)")]  
  20.         [Display(Name = "Designation Name")]  
  21.         public string DesignationName { getset; }  
  22.   
  23.         [ForeignKey("DepartmentInfo")]  
  24.         [Required]  
  25.         public int DepartmentId { getset; }  
  26.   
  27.         [NotMapped]  
  28.         public string DepartmentName { getset; }  
  29.           
  30.         public virtual Department DepartmentInfo { getset; }  
  31.     }  
  32. }  

Step 3

Also, we marked the DepartmentDesc as NotMapped since we did not want to create any column in the designation table with such a name. We will use the attribute simply for displaying the data in the view.

Step 4

Now, we create another class named EFDataContext where we inherit the DBContext class of the Entity Framework and Create the DBSet objects of Department and Designation Class. Also, we override the OnConfiguring() method to provide the database connection details where we need to create the database as per the Entity model class.
  1. using DataContextLayer.Models;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Data.SqlClient;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace DataContextLayer.DataContext  
  11. {  
  12.     public class EFDataContext : DbContext  
  13.     {  
  14.         public DbSet<Department> Departments { getset; }  
  15.   
  16.         public DbSet<Designation> Designations { getset; }  
  17.   
  18.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  19.         {  
  20.             optionsBuilder.UseSqlServer(@"data source=serverName; initial catalog=TestDB;persist security info=True;user id=sa");  
  21.         }                    
  22.     }  
  23. }  
Steps to Automate Migration

Step 1

Now, it's time to automate the migration from our entity class to the database objects. So for this, open the Nuget Package Manager Console Under the Nuget Package Manager Menu and run the command add-migration in the console. It will create the migration files on the basis of the Entity Model class as we defined.
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 
 
The above command creates a Migration file as the below image shown and also create a Migration to the store that file. Now we need to run this migration file to create or update the database.
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 

For creating or updating the database, run the command Update-Database in the console and then check the SQL server for the database and tables objects.

ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 

Now check the database Object Explorer,

ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 
 
Now, we will create views from where we can create or edit or view Department or Designation Data. For this purpose, we need to add another project in the Solution Web Application Projects as the below image.
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 
 
Now Click on the Ok Button and then select Model View Controller Temlpate in the Template window and click on the OK Button.
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 
 
Now, Select the Controller Folder and Click on Add Controller Options,
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 
 
On clicking on Add Button, it will create an Empty Controller with the Index Action Method. Now Right Click on the Index() and Click on Add View Options and then select the options as below,
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 
 
On Clicking on Add Button, it will automatically scaffold the list view page of the department. Now, add another action method named create() in the department controller and then again click on the add view options to the view for creating the view for the department insert.
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach 
 
Below is the complete code of the DepartmentController, Department List View and Deparment Create View. We also use the same Create view for editing the department. For this we will change a small part in the view to fit the requirements.
 
DepartmentController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using DataContextLayer.DataContext;  
  6. using DataContextLayer.Models;  
  7. using Microsoft.AspNetCore.Mvc;  
  8.   
  9. namespace WebAppLayer.Controllers  
  10. {  
  11.     public class DepartmentsController : Controller  
  12.     {  
  13.   
  14.         EFDataContext _dbContext = new EFDataContext();  
  15.   
  16.         public IActionResult Index()  
  17.         {  
  18.             List<Department> data = this._dbContext.Departments.ToList();  
  19.             return View(data);  
  20.         }  
  21.   
  22.         public IActionResult Create()  
  23.         {  
  24.             return View();  
  25.         }  
  26.   
  27.         [HttpPost]  
  28.         public IActionResult Create(Department model)  
  29.         {  
  30.             ModelState.Remove("DepartmentId");  
  31.             if (ModelState.IsValid)  
  32.             {  
  33.                 _dbContext.Departments.Add(model);  
  34.                 _dbContext.SaveChanges();  
  35.                 return RedirectToAction("Index");  
  36.             }  
  37.             return View();  
  38.         }  
  39.   
  40.         public IActionResult Edit(int id)  
  41.         {  
  42.             Department data = _dbContext.Departments.Where(p => p.DepartmentId == id).FirstOrDefault();  
  43.             return View("Create", data);  
  44.         }  
  45.   
  46.         [HttpPost]  
  47.         public IActionResult Edit(Department model)  
  48.         {  
  49.             ModelState.Remove("DepartmentId");  
  50.             if (ModelState.IsValid)  
  51.             {  
  52.                 _dbContext.Departments.Update(model);  
  53.                 _dbContext.SaveChanges();  
  54.                 return RedirectToAction("Index");  
  55.             }  
  56.             return View("Create", model);  
  57.         }  
  58.   
  59.         public IActionResult Delete(int id)  
  60.         {  
  61.             Department data = _dbContext.Departments.Where(p => p.DepartmentId == id).FirstOrDefault();  
  62.             if (data != null)  
  63.             {  
  64.                 _dbContext.Departments.Remove(data);  
  65.                 _dbContext.SaveChanges();  
  66.             }  
  67.             return RedirectToAction("Index");  
  68.         }  
  69.     }  
  70. }  
Index.cshtml (Department)
  1. @model IEnumerable<DataContextLayer.Models.Department>  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Index";  
  5. }  
  6.   
  7. <strong>Index</strong>  
  8.   
  9. <p>  
  10.     <a asp-action="Create">Create New</a>  
  11. </p>  
  12. <table class="table">  
  13.     <thead>  
  14.         <tr>  
  15.             <th>  
  16.                 @Html.DisplayNameFor(model => model.DepartmentId)  
  17.             </th>  
  18.             <th>  
  19.                 @Html.DisplayNameFor(model => model.DepartmentCode)  
  20.             </th>  
  21.             <th>  
  22.                 @Html.DisplayNameFor(model => model.DepartmentName)  
  23.             </th>  
  24.             <th>  
  25.                 @Html.DisplayNameFor(model => model.Description)  
  26.             </th>  
  27.             <th></th>  
  28.         </tr>  
  29.     </thead>  
  30.     <tbody>  
  31. @foreach (var item in Model) {  
  32.         <tr>  
  33.             <td>  
  34.                 @Html.DisplayFor(modelItem => item.DepartmentId)  
  35.             </td>  
  36.             <td>  
  37.                 @Html.DisplayFor(modelItem => item.DepartmentCode)  
  38.             </td>  
  39.             <td>  
  40.                 @Html.DisplayFor(modelItem => item.DepartmentName)  
  41.             </td>  
  42.             <td>  
  43.                 @Html.DisplayFor(modelItem => item.Description)  
  44.             </td>  
  45.             <td>  
  46.                 @Html.ActionLink("Edit""Edit"new { id = item.DepartmentId }) |  
  47.                 @Html.ActionLink("Delete""Delete"new { id = item.DepartmentId }, new { onclick = "return confirm('Are you sure to delete?')" })  
  48.             </td>  
  49.         </tr>  
  50. }  
  51.     </tbody>  
  52. </table>  
Creatte.cshtml (Department)
  1. @model DataContextLayer.Models.Department  
  2.   
  3. @{  
  4.     ViewData["Title"] = Model != null ? "Edit" : "Create";  
  5. }  
  6.   
  7. <strong>@ViewData["Title"]</strong>  
  8.   
  9. <h4>Department</h4>  
  10. <hr />  
  11. <div class="row">  
  12.     <div class="col-md-4">  
  13.         <form asp-action="@ViewData["Title"]">  
  14.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  15.             <input type="hidden" asp-for="DepartmentId" class="form-control" />  
  16.             <div class="form-group">  
  17.                 <label asp-for="DepartmentCode" class="control-label"></label>  
  18.                 <input asp-for="DepartmentCode" class="form-control" />  
  19.                 <span asp-validation-for="DepartmentCode" class="text-danger"></span>  
  20.             </div>  
  21.             <div class="form-group">  
  22.                 <label asp-for="DepartmentName" class="control-label"></label>  
  23.                 <input asp-for="DepartmentName" class="form-control" />  
  24.                 <span asp-validation-for="DepartmentName" class="text-danger"></span>  
  25.             </div>  
  26.             <div class="form-group">  
  27.                 <label asp-for="Description" class="control-label"></label>  
  28.                 <input asp-for="Description" class="form-control" />  
  29.                 <span asp-validation-for="Description" class="text-danger"></span>  
  30.             </div>  
  31.             <div class="form-group">  
  32.                 <input type="submit" value="Save" class="btn btn-default" />  
  33.             </div>  
  34.         </form>  
  35.     </div>  
  36. </div>  
  37.   
  38. <div>  
  39.     <a asp-action="Index">Back to List</a>  
  40. </div>  
  41.   
  42. @section Scripts {  
  43.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  44. }  
Similarly, we need to create the Designation Controller and its related view for displaying or creating or editing the data.
 
DesignationController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using DataContextLayer.DataContext;  
  6. using DataContextLayer.Models;  
  7. using Microsoft.AspNetCore.Mvc;  
  8.   
  9. namespace WebAppLayer.Controllers  
  10. {  
  11.     public class DesignationsController : Controller  
  12.     {  
  13.         EFDataContext _dbContext = new EFDataContext();  
  14.   
  15.         public IActionResult Index()  
  16.         {  
  17.             //List<Designation> data = _dbContext.Designations.ToList();  
  18.   
  19.             var data = (from dept in _dbContext.Departments  
  20.                         join desig in _dbContext.Designations  
  21.                         on dept.DepartmentId equals desig.DepartmentId  
  22.                         select new Designation  
  23.                         {  
  24.                             DesignationId = desig.DesignationId,  
  25.                             DesignationCode = desig.DesignationCode,  
  26.                             DesignationName = desig.DesignationName,  
  27.                             DepartmentId = desig.DepartmentId,  
  28.                             DepartmentName = dept.DepartmentName  
  29.                         }).ToList();  
  30.   
  31.             return View(data);  
  32.         }  
  33.   
  34.         public IActionResult Create()  
  35.         {  
  36.             ViewBag.Departments = _dbContext.Departments.ToList();  
  37.             return View();  
  38.         }  
  39.   
  40.         [HttpPost]  
  41.         public IActionResult Create(Designation model)  
  42.         {  
  43.             ModelState.Remove("DesignationId");  
  44.             if (ModelState.IsValid)  
  45.             {  
  46.                 _dbContext.Designations.Add(model);  
  47.                 _dbContext.SaveChanges();  
  48.                 return RedirectToAction("Index");  
  49.             }  
  50.             ViewBag.Departments = _dbContext.Departments.ToList();  
  51.             return View();  
  52.         }  
  53.   
  54.         public IActionResult Edit(int id)  
  55.         {  
  56.             Designation data = _dbContext.Designations.Where(p => p.DesignationId == id).FirstOrDefault();  
  57.             ViewBag.Departments = _dbContext.Departments.ToList();  
  58.             return View("Create", data);  
  59.         }  
  60.   
  61.         [HttpPost]  
  62.         public IActionResult Edit(Designation model)  
  63.         {  
  64.             ModelState.Remove("DesignationId");  
  65.             if (ModelState.IsValid)  
  66.             {  
  67.                 _dbContext.Designations.Update(model);  
  68.                 _dbContext.SaveChanges();  
  69.                 return RedirectToAction("Index");  
  70.             }  
  71.             ViewBag.Departments = _dbContext.Departments.ToList();  
  72.             return View("Create", model);  
  73.         }  
  74.   
  75.         public IActionResult Delete(int id)  
  76.         {  
  77.             Designation data = _dbContext.Designations.Where(p => p.DesignationId == id).FirstOrDefault();  
  78.             if (data != null)  
  79.             {  
  80.                 _dbContext.Designations.Remove(data);  
  81.                 _dbContext.SaveChanges();  
  82.             }  
  83.             return RedirectToAction("Index");  
  84.         }  
  85.     }  
  86. }  
Index.cshtml (Designation)
  1. @model IEnumerable<DataContextLayer.Models.Designation>  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Index";  
  5. }  
  6.   
  7. <strong>Index</strong>  
  8.   
  9. <p>  
  10.     <a asp-action="Create">Create New</a>  
  11. </p>  
  12. <table class="table">  
  13.     <thead>  
  14.         <tr>  
  15.             <th>  
  16.                 @Html.DisplayNameFor(model => model.DesignationId)  
  17.             </th>  
  18.             <th>  
  19.                 @Html.DisplayNameFor(model => model.DesignationCode)  
  20.             </th>  
  21.             <th>  
  22.                 @Html.DisplayNameFor(model => model.DesignationName)  
  23.             </th>              
  24.             <th>  
  25.                 @Html.DisplayNameFor(model => model.DepartmentName)  
  26.             </th>  
  27.             <th></th>  
  28.         </tr>  
  29.     </thead>  
  30.     <tbody>  
  31. @foreach (var item in Model) {  
  32.         <tr>  
  33.             <td>  
  34.                 @Html.DisplayFor(modelItem => item.DesignationId)  
  35.             </td>  
  36.             <td>  
  37.                 @Html.DisplayFor(modelItem => item.DesignationCode)  
  38.             </td>  
  39.             <td>  
  40.                 @Html.DisplayFor(modelItem => item.DesignationName)  
  41.             </td>              
  42.             <td>  
  43.                 @Html.DisplayFor(modelItem => item.DepartmentName)  
  44.             </td>  
  45.             <td>  
  46.                 @Html.ActionLink("Edit""Edit"new {  id=item.DesignationId  }) |  
  47.                 @Html.ActionLink("Delete""Delete"new {  id=item.DesignationId  })  
  48.             </td>  
  49.         </tr>  
  50. }  
  51.     </tbody>  
  52. </table>  
create.cshtml
  1. @model DataContextLayer.Models.Designation  
  2.   
  3. @{  
  4.     ViewData["Title"] = Model != null ? "Edit" : "Create";  
  5. }  
  6.   
  7. <strong>@ViewData["Title"]</strong>  
  8.   
  9. <h4>Designation</h4>  
  10. <hr />  
  11. <div class="row">  
  12.     <div class="col-md-4">  
  13.         <form asp-action="@ViewData["Title"]">  
  14.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  15.             <input type="hidden" asp-for="DesignationId" class="form-control" />  
  16.             <div class="form-group">  
  17.                 <label asp-for="DesignationCode" class="control-label"></label>  
  18.                 <input asp-for="DesignationCode" class="form-control" />  
  19.                 <span asp-validation-for="DesignationCode" class="text-danger"></span>  
  20.             </div>  
  21.             <div class="form-group">  
  22.                 <label asp-for="DesignationName" class="control-label"></label>  
  23.                 <input asp-for="DesignationName" class="form-control" />  
  24.                 <span asp-validation-for="DesignationName" class="text-danger"></span>  
  25.             </div>  
  26.   
  27.             <div class="form-group">  
  28.                 <label asp-for="DepartmentId" class="control-label"></label>  
  29.                 <select asp-for="DepartmentId" asp-items="@(new SelectList(ViewBag.Departments,"DepartmentId","DepartmentName"))" class="form-control">  
  30.                     <option value="">--Select--</option>  
  31.                 </select>  
  32.                 <span asp-validation-for="DepartmentId" class="text-danger"></span>  
  33.             </div>  
  34.             <div class="form-group">  
  35.                 <input type="submit" value="Save" class="btn btn-default" />  
  36.             </div>  
  37.         </form>  
  38.     </div>  
  39. </div>  
  40.   
  41. <div>  
  42.     <a asp-action="Index">Back to List</a>  
  43. </div>  
  44.   
  45. @section Scripts {  
  46.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  47. }  N
Now, run the application in the browser and it will show you the below result,
 
ASP.NET Core 2.1 - Implement Entity Framework Core In A Code First Approach
Conclusion
 
So, in this article we will discuss about the basic concept of the Code First Approach and also discuss how to implement this code first approach in the Entity Framework Core. For any further query or clarification, ping me.