Entity Framework Core (EF Core) is one of the latest data access technologies for any type of application in the .NET Core framework. Entity Framework Core is based on Object-Relational Mapper or ORM model. Basically, the object-relational model is a technique that helps the developer to establish a relation between the entity model class of the application and the data objects of the relational database. In this technique, developers can create a relation between the entity model class and database objects, i.e., tables in the relational database in an object-oriented way to perform different types of operations like fetch data, save data, etc. Entity Framework Core is a lightweight extensible framework which can support cross-platform development.
Entity Framework Core provides a lot of benefits to the concept of rapid developments. The main advantages of Entity Framework Core are:
- Entity framework core provides auto generated code.
- It helps us to reduce development time.
- It also helps us to reduce development cost.
- Using this framework, developers can visually design entity models and can map the database objects.
- It provides a multiple conceptual model to map with a single schema object.
PREREQUISITES REQUIRED
In this article, we will discuss how to develop an application using Entity Framework Core. In this application, we can perform the following operations:
- Basic CRUD Operations like Insert, Update, Delete & Read
- Sort Record
- Search Record
- Paging Data for Listing
- Download Index List Data as Excel File
For starting this development, we need to have the below prerequisites.
- Microsoft Visual Studio 2017
- .Net Core 2.1 or Above SDK
- Relation Database like SQL Server
CREATE DATABASE USING ENTITY FRAMEWORK CORE CODE FIRST APPROACH
Step 1
Now, open Microsoft Visual Studio 2017 and click on File --> New --> Projects.

Step 2
Select the Web Application Project template and click the OK button.

Step 3
In the Project Template Box, select Web Application (Model-View-Controller) options and click on the OK button.
Step 4
Now, a blank project solution has been ready.
Step 5
Now, select the solution file and right-click and select Add --> New Projects.
Step 6
Now, select Class Library (.NET Core) Project Template
Step 7
Provide a Project Name as DataContext and click OK.

Step 8
Now, install the below Nuget Packages related to the Entity Framework Core.
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools

Step 9
Now, create a folder called Models in this project and add the below models.
Department.cs --> Department class which contains Department name list
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Text;
- namespace DataContext.Models
- {
- [Table("Department", Schema = "dbo")]
- public class Department
- {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- [Display(Name = "Department Id")]
- public int DepartmentId { get; set; }
- [Required]
- [Column(TypeName = "NVarchar(20)")]
- [Display(Name = "Department Code")]
- public string Alias { get; set; }
- [Required]
- [Column(TypeName = "Nvarchar(100)")]
- [Display(Name = "Department Description")]
- public string DepartmentName { get; set; }
- }
- }
Designation.cs --> Designation class which contains Designation Name List
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Text;
- namespace DataContext.Models
- {
- [Table("Designation", Schema = "dbo")]
- public class Designation
- {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public int DesignationId { get; set; }
- [Required]
- [Column(TypeName = "NVarchar(20)")]
- [Display(Name = "Designation Code")]
- public string DesignationCode { get; set; }
- [Required]
- [Column(TypeName = "varchar(100)")]
- [Display(Name = "Designation Name")]
- public string DesignationName { get; set; }
- }
- }
Employee.cs --> Employee class which contains Employee details List. In this entity, DepartmentId and DesignationId is acting as a Foreign Key related to the Department and Designation Entity.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Text;
- namespace DataContext.Models
- {
- [Table("Employee", Schema = "dbo")]
- public class Employee
- {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- [Display(Name = "Employee Id")]
- public int Id { get; set; }
- [Required]
- [Column(TypeName = "NVarchar(20)")]
- [Display(Name = "Code")]
- public string EmployeeCode { get; set; }
- [Required]
- [Column(TypeName = "NVarchar(100)")]
- [Display(Name = "Employee Name")]
- public string EmployeeName { get; set; }
- [Required]
- [Column(TypeName = "DateTime2")]
- [Display(Name = "Date of Birth")]
- [DataType(DataType.Date)]
- public DateTime DateOfBirth { get; set; }
- [Required]
- [Column(TypeName = "DateTime2")]
- [Display(Name = "Join Date")]
- [DataType(DataType.Date)]
- public DateTime JoinDate { get; set; }
- [Required]
- [Column(TypeName = "Decimal(18,2)")]
- public decimal Salary { get; set; }
- [Column(TypeName = "NVarchar(100)")]
- public string Address { get; set; }
- [Column(TypeName = "NVarchar(100)")]
- public string State { get; set; }
- [Column(TypeName = "NVarchar(100)")]
- public string City { get; set; }
- [Column(TypeName = "NVarchar(20)")]
- public string ZipCode { get; set; }
- [ForeignKey("DepartmentInfo")]
- [Required]
- public int DepartmentId { get; set; }
- [Display(Name = "Department")]
- [NotMapped]
- public string DepartmentName { get; set; }
- public virtual Department DepartmentInfo { get; set; }
- [ForeignKey("DesignationInfo")]
- [Required]
- public int DesignationId { get; set; }
- [Display(Name = "Designation")]
- [NotMapped]
- public string DesignationName { get; set; }
- public virtual Designation DesignationInfo { get; set; }
- }
- }
Step 10
Now, create another folder called DataContext.
Step 11
Within this folder, add the class file name EFDataContext.cs which will contains mapping code related to the entity and database tables. Now, add the below code in this file.
- using DataContext.Models;
- using Microsoft.EntityFrameworkCore;
- using System;
- using System.Collections.Generic;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Text;
- namespace DataContext.DataContext
- {
- public class EFDataContext : DbContext
- {
- public DbSet<Department> Departments { get; set; }
- public DbSet<Designation> Designations { get; set; }
- public DbSet<Employee> Employees { get; set; }
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- optionsBuilder.UseSqlServer(@"data source=xxx; initial catalog=EFCrudDemo;persist security info=True;user id=sa;password=ssss;");
- }
- }
Step 12
In the above file, we overrode the method OnConfiguring() of the DBContext to specify the database and sql server credentials so that Entity Framework Core can connect with the database server for the CRUD operations in the applications.
Step 13
Now, open the Package Manager Console and run the below command – add migration migration1 (here migration1 is the alias name which can be changed).
Step 14
Now, run the command update database.
Step 15
Now, open the SQL Server and check the mentioned database is already created.
Step 16
Now, in this application, we will create a CRUD operation for Employee data objects. So, we need to insert sample data using a database in the Department and Designation tables so that when we will try to create employee from the application we can generate the department and designation lists.
CREATE EMPLOYEE INDEX UI
Step 1
Now select the DemoApplication Projects (MVC Application) and provide the reference of the DataContext Library which we already add.
Step 2
Now Select the Controller Folder and right click and select Add --> Controller.
Step 3
In the Controller Template, Select MVC Controller – Empty and click on Add Button
Step 4
Provide the Controller Name as EmployeesController and Click on Ok Button.
Step 5
Now in the controller file, create an object for EFDataContext class as below -
- EFDataContext _dbContext = new EFDataContext();
Now in the controller file, add a method named Index and write down the below code -
- public class EmployeesController : Controller
- {
- EFDataContext _dbContext = new EFDataContext();
- public IActionResult Index()
- {
- List<Employee> employees = this._dbContext.Employees.ToList();
- return View(employees);
- }
- }
In the View Folder, create a new folder called Employee and then add an empty view named index.cshtml.
Step 8
Now open the Index.cshtml view and the the below code.
- @model IEnumerable<DataContext.Models.Employee>
- @{
- ViewData["Title"] = "Employee List";
- }
- <h1>Index</h1>
- <p>
- <a asp-action="Create">Create New</a>
- </p>
- <table class="table">
- <thead>
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.EmployeeCode)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.EmployeeName)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.DateOfBirth)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.JoinDate)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.DepartmentName)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.DesignationName)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Salary)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.State)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.City)
- </th>
- <th></th>
- </tr>
- </thead>
- <tbody>
- @foreach (var item in Model) {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.EmployeeCode)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.EmployeeName)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.DateOfBirth)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.JoinDate)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.DepartmentName)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.DesignationName)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Salary)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.State)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.City)
- </td>
- <td>
- @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
- @Html.ActionLink("Delete", "Delete", new { id = item.Id })
- </td>
- </tr>
- }
- </tbody>
- </table>
Step 9
Now open the _Layout.cshtml view in shared folder and the below line of code in that file:
- <header>
- <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
- <div class="container">
- <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">EF_Crud_Samples</a>
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
- aria-expanded="false" aria-label="Toggle navigation">
- <span class="navbar-toggler-icon"></span>
- </button>
- <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
- <ul class="navbar-nav flex-grow-1">
- <li class="nav-item">
- <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
- </li>
- <li class="nav-item">
- <a class="nav-link text-dark" asp-area="" asp-controller="Employees" asp-action="Index">Employee</a>
- </li>
- <li class="nav-item">
- <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
- </li>
- </ul>
- </div>
- </div>
- </nav>
- </header>
Now run the application and click on Employee Link

CREATE NEW EMPLOYEE UI
Step 1
Now, open the EmployeesController.cs file again and add a new method as below:
- public IActionResult Create()
- {
- this.GetModelData();
- return View();
- }
- private void GetModelData()
- {
- ViewBag.Departments = this._dbContext.Departments.ToList();
- ViewBag.Designations = this._dbContext.Designations.ToList();
- }
In the above method, we create two ViewBag inststances for Department and Designation Lists.
Step 3
Now Select the Employee folder under views and add another empty view. Create.cshtml and add the below code in that file.
- @model DataContext.Models.Employee
- @{
- ViewData["Title"] = Model != null ? "Edit" : "Create";
- }
- <h2>@ViewData["Title"] Employee</h2>
- <hr />
- <div class="row">
- <div class="col-lg-12">
- <form asp-action="ViewData[" Title"]">
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <div class="form-group">
- <div class="form-row">
- <div class="col-lg-2">
- <label asp-for="EmployeeCode" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <input asp-for="EmployeeCode" class="form-control" />
- <span asp-validation-for="EmployeeCode" class="text-danger"></span>
- </div>
- <div class="col-lg-2">
- <label asp-for="EmployeeName" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <input asp-for="EmployeeName" class="form-control" />
- <span asp-validation-for="EmployeeName" class="text-danger"></span>
- </div>
- </div>
- <div class="form-row">
- <div class="col-lg-2">
- <label asp-for="DateOfBirth" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <input asp-for="DateOfBirth" class="form-control" />
- <span asp-validation-for="DateOfBirth" class="text-danger"></span>
- </div>
- <div class="col-lg-2">
- <label asp-for="JoinDate" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <input asp-for="JoinDate" class="form-control" />
- <span asp-validation-for="JoinDate" class="text-danger"></span>
- </div>
- </div>
- <div class="form-row">
- <div class="col-lg-2">
- <label asp-for="DepartmentId" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <select asp-for="DepartmentId" asp-items="@(new SelectList(ViewBag.Departments,"DepartmentId","DepartmentName"))" class="form-control">
- <option value="">--Select--</option>
- </select>
- <span asp-validation-for="DepartmentId" class="text-danger"></span>
- </div>
- <div class="col-lg-2">
- <label asp-for="DesignationId" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <select asp-for="DesignationId" asp-items="@(new SelectList(ViewBag.Designations,"DesignationId","DesignationName"))" class="form-control">
- <option value="">--Select--</option>
- </select>
- <span asp-validation-for="DesignationId" class="text-danger"></span>
- </div>
- </div>
- <div class="form-row">
- <div class="col-lg-2">
- <label asp-for="Salary" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <input asp-for="Salary" class="form-control" />
- <span asp-validation-for="Salary" class="text-danger"></span>
- </div>
- <div class="col-lg-2">
- </div>
- <div class="col-lg-4">
- </div>
- </div>
- <div class="form-row">
- <div class="col-lg-2">
- <label asp-for="Address" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <input asp-for="Address" class="form-control" />
- <span asp-validation-for="Address" class="text-danger"></span>
- </div>
- <div class="col-lg-2">
- <label asp-for="State" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <input asp-for="State" class="form-control" />
- <span asp-validation-for="State" class="text-danger"></span>
- </div>
- </div>
- <div class="form-row">
- <div class="col-lg-2">
- <label asp-for="City" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <input asp-for="City" class="form-control" />
- <span asp-validation-for="City" class="text-danger"></span>
- </div>
- <div class="col-lg-2">
- <label asp-for="ZipCode" class="control-label"></label>
- </div>
- <div class="col-lg-4">
- <input asp-for="ZipCode" class="form-control" />
- <span asp-validation-for="ZipCode" class="text-danger"></span>
- </div>
- </div>
- <div class="form-row">
- <hr />
- </div>
- <div class="form-row">
- <div class="col-lg-3">
- </div>
- <div class="col-lg-7">
- <input type="submit" value="Save" class="btn btn-primary" />
- <a asp-action="Index" class="btn btn-secondary">Cancel</a>
- </div>
- </div>
- </div>
- </form>
- </div>
- </div>
- @section Scripts {
- @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
- }






Jomis PjPosted Apr 14, 2023, 6:27 AM
Nice Article.
Ravindra GuptaPosted Dec 7, 2022, 8:44 PM
Very good articles.
Mah HingPosted Apr 12, 2021, 2:59 AM
If there are three or more pages the sorting order is reverted: for example page 1 is employee name asc, page2 employee name desc, page 3 employee name asc again. How to fix this?
Regin VPosted Mar 17, 2021, 7:15 PM
Thank you! This really helped. Especially how you incrementally add features in working units which makes it easy to follow. Great job!
Bhaskar BanerjeePosted Oct 28, 2020, 8:09 AM
Sir, Can you suggest or upload some code on Dot Net Core, how to work on Custom Role Based Authorization stored in Database Table. Means, Superuser or Administrator will create some role and allowed some Access Rights which stored in database table. Users tagged with that specific Role, will be authorized to do allowed operations. No Hard Coded Role name in Controller, all will be based on Table. Thanks in advance.
Jon JohnPosted Oct 6, 2020, 5:10 AM
Please please try to provide full code or dont provide
Ramzanali MominPosted Nov 6, 2019, 4:02 AM
Thanks are very useful information. Please design the cascading dropdown list article in Angular with web api core a and database sql server 2008
Chittaranjan SwainPosted Oct 31, 2019, 7:36 AM
Very useful article....
Maurice AboagyePosted Oct 25, 2019, 1:47 PM
Thanx Debassis Saha for guide me to export the Index view to Microsoft Excel. I believe many others will also benefit from this. Thanx very much.
Maurice AboagyePosted Oct 10, 2019, 4:16 AM
Hello Debassis Saha. PLease guide me to export the results of the Index View In This Project to Microsoft Excel. Thanx in advance.
Maurice AboagyePosted Sep 16, 2019, 2:22 PM
Thanx vey much Debassis Saha. You ve shed the light
Paolo ScottiPosted Aug 30, 2019, 2:44 PM
Hello, I tried to launch your project but it gives me HTTP Error 502.5 - Process Failure
alex zPosted Aug 29, 2019, 11:09 AM
Can you provide a function for search box witch if no result a modal open and ask if you want to add? ex : search for a city and if no data found ..result "This city not exist .Do you want to crate? Yes / No.and if press yes open modal with create city or any else ?
Heràclides MoralesPosted May 3, 2019, 9:26 PM
Thank you very much for your help graciassss
Heràclides MoralesPosted May 3, 2019, 12:59 PM
Con el respeto debido si es tan gentil indicarme como debo hacerlo ya que soy nuevo en .net core e intentado de la siguiente manera pero no me funciona (add_migration migration1 -StartupProjectName "DataContext") muy agradecido de su parte por su ayuda
Heràclides MoralesPosted May 3, 2019, 10:17 AM
Muy buen ejemplo. por favor me podrian ayudar con este error No DbContext was found in assembly 'EF_Crud_Samples'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.