CRUD Operations in ASP.NET Core MVC Using Entity Framework Core – Step-by-Step Guide
Introduction
In this article, we will learn how to perform CRUD operations in ASP.NET Core MVC using Entity Framework Core and SQL Server.
CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that we perform while working with a database in almost every application.
In my previous article, we implemented CRUD operations using ADO.NET, where we manually wrote SQL queries and used SqlConnection, SqlCommand, and SqlDataReader to interact with the database.
In this article, we will use Entity Framework Core, which simplifies database operations and allows us to work with database records using C# objects and LINQ.
For this demonstration, we will create a simple Employee Management application using the Code First approach.
What We Will Implement
- Display all employees.
- Add a new employee.
- Edit existing employee details.
- Delete an employee.
- Implement model validation.
- Configure Entity Framework Core.
- Create a database using migrations.
- Implement dependency injection.
Technologies Used
- ASP.NET Core MVC (.NET 8)
- C#
- Entity Framework Core 8
- LINQ
- Microsoft SQL Server
- Razor Views
- Bootstrap
- Visual Studio
Step 1: Create an ASP.NET Core MVC Project
Open Visual Studio and follow the steps below:
- Click on Create a new project.
- Select ASP.NET Core Web App (Model-View-Controller).
- Enter the project name as
CrudPractice. - Select .NET 8 as the framework.
- Select None as the authentication type.
- Click on Create.
Once the project is created, we will create the required Model, DbContext, DAL, Controller, and Views.
Step 2: Install the Required NuGet Packages
To work with Entity Framework Core and SQL Server, we need to install the following NuGet packages.
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.Design
Right-click on the project and select Manage NuGet Packages.
Search for the above packages and install compatible EF Core 8.0.x versions. Keep all three packages on the same version.
Understanding the Packages
| Package | Purpose |
|---|---|
| EntityFrameworkCore.SqlServer | Provides SQL Server database connectivity |
| EntityFrameworkCore.Tools | Provides migration commands in Package Manager Console |
| EntityFrameworkCore.Design | Provides design-time services for migrations |
Step 3: Create the Employee Model
Inside the Models folder, create a class named Employee.cs.
using System.ComponentModel.DataAnnotations;
namespace CrudPractice.Models
{
public class Employee
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(100)]
public string? Name { get; set; }
[EmailAddress(ErrorMessage = "Invalid email address")]
[StringLength(150)]
public string? Email { get; set; }
[Required(ErrorMessage = "Department is required")]
[StringLength(100)]
public string? Department { get; set; }
[Range(typeof(decimal), "0", "9999999999999999.99",
ErrorMessage = "Enter a valid non-negative salary")]
public decimal? Salary { get; set; }
}
}Understanding the Model
The Employee model represents the structure of our Employee table.
In the Code First approach, Entity Framework Core uses our model classes and database configuration to generate the database schema through migrations.
Here, we are using Data Annotations to implement validation.
- Required: Ensures that the field is not empty.
- EmailAddress: Validates the email format.
- StringLength: Restricts the maximum length of a string.
- Range: Restricts the salary to an allowed range.
Entity Framework Core automatically identifies the Id property as the primary key by convention.
Email and Salary are optional fields in this application.
Step 4: Create the Database Context
Create a new folder named Data inside the project.
Inside this folder, create a class named ApplicationDbContext.cs.
using CrudPractice.Models;
using Microsoft.EntityFrameworkCore;
namespace CrudPractice.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Employee>()
.ToTable("Employee");
modelBuilder.Entity<Employee>()
.Property(e => e.Salary)
.HasPrecision(18, 2);
}
}
}What Is DbContext?
DbContext is one of the most important classes in Entity Framework Core.
It acts as a bridge between our application and the database.
It is responsible for:
- Managing database connections.
- Querying database records.
- Tracking changes in entities.
- Inserting, updating, and deleting records.
- Saving changes to the database.
What Is DbSet?
DbSet represents a collection of entities that can be queried and saved in the database.
public DbSet<Employee> Employees { get; set; }Here, Employees represents the Employee entity collection.
We are using ToTable("Employee") to explicitly specify the database table name.
We are also using HasPrecision(18, 2) to configure the Salary column as DECIMAL(18,2) in SQL Server.
Step 5: Configure the Connection String
Open the appsettings.json file and add the following connection string.
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=CrudPracticeEFDB;Trusted_Connection=True;TrustServerCertificate=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}Replace the server name according to your SQL Server instance.
Here, we are using a separate database named CrudPracticeEFDB so that it does not conflict with the database created in the previous ADO.NET application.
TrustServerCertificate is enabled for local development. In production, use a trusted SQL Server certificate and proper certificate validation.
Step 6: Register DbContext Using Dependency Injection
Open the Program.cs file and register ApplicationDbContext.
using CrudPractice.Data;
using Microsoft.EntityFrameworkCore;Add the following code before builder.Build().
builder.Services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(
builder.Configuration
.GetConnectionString("DefaultConnection")));The AddDbContext method registers our ApplicationDbContext with the dependency injection container.
By default, DbContext is registered with a Scoped lifetime, which means that one instance is created per HTTP request.
The UseSqlServer method specifies that we are using SQL Server as our database provider.
Step 7: Create Database Using Migrations
Since we are using the Code First approach, there is no need to manually create the database and tables.
Entity Framework Core migrations will help us create them automatically.
Open:
Tools → NuGet Package Manager → Package Manager Console
Make sure CrudPractice is selected as the default project and startup project.
Execute the following command:
Add-Migration InitialCreateThis command generates a Migrations folder containing the code required to create our database structure.
Now execute:
Update-DatabaseThis command applies the migration to SQL Server.
Open SQL Server Management Studio and refresh the Databases folder.
You should find the following database and tables:
CrudPracticeEFDB
│
└── Tables
├── dbo.Employee
└── dbo.__EFMigrationsHistoryThe Employee table stores employee information.
The __EFMigrationsHistory table is maintained by Entity Framework Core to keep track of applied migrations.
Insert Sample Records
We can also insert some sample records using SQL Server Management Studio.
USE CrudPracticeEFDB;
GO
INSERT INTO Employee
(Name, Email, Department, Salary)
VALUES
('Rahul Sharma', '[email protected]', 'IT', 35000),
('Amit Singh', '[email protected]', 'HR', 30000),
('Priya Gupta', '[email protected]', 'Finance', 40000);This step is optional because we can also add employees directly from our application.
Step 8: Create the Data Access Layer (DAL)
Create a new folder named DAL inside the project.
Inside this folder, create a class named EmployeeDAL.cs.
Although we can directly use ApplicationDbContext inside the Controller, we will create a separate Data Access Layer to keep database-related operations separate from Controller logic.
EmployeeDAL.cs
using CrudPractice.Data;
using CrudPractice.Models;
namespace CrudPractice.DAL
{
public class EmployeeDAL
{
private readonly ApplicationDbContext _context;
public EmployeeDAL(ApplicationDbContext context)
{
_context = context;
}
public List<Employee> GetAllEmployee()
{
return _context.Employees.ToList();
}
public void AddEmployee(Employee emp)
{
_context.Employees.Add(emp);
_context.SaveChanges();
}
public Employee? GetEmployeeById(int id)
{
return _context.Employees.Find(id);
}
public void UpdateEmployee(Employee emp)
{
var employee = _context.Employees.Find(emp.Id);
if (employee != null)
{
employee.Name = emp.Name;
employee.Email = emp.Email;
employee.Department = emp.Department;
employee.Salary = emp.Salary;
_context.SaveChanges();
}
}
public void DeleteEmployee(int id)
{
var emp = _context.Employees.Find(id);
if (emp != null)
{
_context.Employees.Remove(emp);
_context.SaveChanges();
}
}
}
}Understanding the CRUD Operations
Let's understand each method one by one.
Read Operation
public List<Employee> GetAllEmployee()
{
return _context.Employees.ToList();
}The ToList() method executes the query and returns all employee records as a list.
Entity Framework Core generates and executes the required SELECT query internally.
The equivalent SQL operation is:
SELECT * FROM Employee;Create Operation
public void AddEmployee(Employee emp)
{
_context.Employees.Add(emp);
_context.SaveChanges();
}The Add() method marks the Employee entity for insertion.
The SaveChanges() method executes the required INSERT operation in the database.
The equivalent SQL operation is:
INSERT INTO Employee
(Name, Email, Department, Salary)
VALUES
(@Name, @Email, @Department, @Salary);Get Employee by ID
public Employee? GetEmployeeById(int id)
{
return _context.Employees.Find(id);
}The Find() method searches for an entity using its primary key.
It first checks whether the entity is already being tracked by DbContext. If not, it queries the database.
If no record is found, it returns null.
Update Operation
public void UpdateEmployee(Employee emp)
{
var employee = _context.Employees.Find(emp.Id);
if (employee != null)
{
employee.Name = emp.Name;
employee.Email = emp.Email;
employee.Department = emp.Department;
employee.Salary = emp.Salary;
_context.SaveChanges();
}
}First, we fetch the existing employee from the database.
After that, we update the required properties.
Entity Framework Core automatically tracks these changes and generates the required UPDATE statement when SaveChanges() is called.
This is known as Change Tracking.
Delete Operation
public void DeleteEmployee(int id)
{
var emp = _context.Employees.Find(id);
if (emp != null)
{
_context.Employees.Remove(emp);
_context.SaveChanges();
}
}First, we check whether the employee exists in the database.
The Remove() method marks the entity for deletion.
The SaveChanges() method executes the DELETE operation.
Understanding Entity Framework Core Methods
| Method | Purpose |
|---|---|
| ToList() | Retrieves records as a list |
| Find() | Finds a record using its primary key |
| Add() | Marks a new entity for insertion |
| Update() | Marks an entity for update |
| Remove() | Marks an entity for deletion |
| SaveChanges() | Saves tracked changes to the database |
Why Are We Using SaveChanges()?
Entity Framework Core tracks the changes made to entities.
Calling Add(), Update(), or Remove() generally changes the state of an entity but does not immediately save those changes to the database.
SaveChanges() generates and executes the required SQL commands for the tracked changes.
Step 9: Register EmployeeDAL Using Dependency Injection
Open the Program.cs file and add the following line:
builder.Services.AddScoped<EmployeeDAL>();The complete Program.cs file will look like this:
Join the conversation! Your thoughts help the community grow.