📌 Introduction
If you're just getting started with backend web development using .NET, learning how to perform CRUD (Create, Read, Update, Delete) operations using ASP.NET Web API and Entity Framework Core is one of the best ways to build real-world skills.
In this blog, we’ll walk step-by-step through creating a simple Employee Management Web API project using:
•✅ ASP.NET 8
•✅ Entity Framework Core (Code First)
•✅ Visual Studio
•✅ SQL Server (Local)
•✅ DTOs for clean architecture
Whether you're new to .NET or just brushing up, this tutorial will help you understand and build a fully working Web API.
🧠 What is ASP.NET Web API?
ASP.NET Web API is a framework that allows you to build RESTful services using HTTP. HTTP-based services that can be consumed by a wide range of clients, including browsers, mobile apps, and desktop applications. It’s RESTful, lightweight, and easy to integrate with frontend applications like React, Angular, or even mobile apps.
🔄 What are CRUD Operations?
CRUD stands for:
•C: Create → Add new data
•R: Read → Get data
•U: Update → Modify data
•D: Delete → Remove data
These operations are the foundation of almost any application that interacts with a database.
🏗️ What is .NET 8?
.NET 8 is the latest LTS (Long-Term Support) version of Microsoft’s unified development platform. It provides improvements in performance, cloud-native features, and simplified APIs for developers.
🧰 What is Entity Framework Core?
Entity Framework Core (EF Core) is an Object Relational Mapper (ORM) that enables .NET developers to interact with the database using C# objects, instead of writing SQL queries manually. With the Code First approach, we define our database schema using C# classes, and EF Core generates the actual database structure.
🔧 Project Setup (Step-by-Step)
✅ Step 1: Create a New Project
- Open Visual Studio
- Click on Create a new project
- Choose ASP.NET Core Web API
- Click Next
- Enter Project Name: ApiCruds
- Choose .NET 8 as the framework 7 . Make sure Use controllers (uncheck minimal API) is selected 8 . Click Create
✅ Step 2: Setup Database Connection
Now go to the solution explorer and open appsettings.json, and you can see this code:
Then, add these ConnectionStrings to connect to your database:
✅ Step 3: Install Required NuGet Packages
Right-click on the solution > Click Manage NuGet Packages > Select Browser > Then Install These Two Packages:
•Microsoft.EntityFrameworkCore.SqlServer
•Microsoft.EntityFrameworkCore.Tools
✅ Step 4: Create Data Folder and DbContext Class
1.Right-click on the project > Add > New Folder > Name it Data
2.Right-click on Data folder > Add > Class > Name it ApplicationDbContext.cs
Now add this code:
📊 Why use ApplicationDbContext?
This class tells EF Core how to connect to your database and what tables (DbSets) it should track. It’s the bridge between your C# code and the database.
✅ Step 5: Register DbContext in Program.cs
Inside the Program.cs file, we need to tell our application how to connect to the database using the ApplicationDbContext class.
Add this line below the builder initialization code:
📘 Explanation:
•builder.Services is used to register services like our DbContext into the Dependency Injection (DI) container.
•AddDbContext tells ASP.NET to manage this class.
•UseSqlServer(...) connects DbContext to SQL Server using the connection string from appsettings.json.
🧠 Without this step, your application won’t know how to connect to the database or which database to use! csharp
✅ Step 6: Create the Employee Model
- Right-click on the project > Add > New Folder>
Models
- Inside
Models
, create another folder namedEntities
- Add a class:
Employee.cs
Then add this code:
📊 Why use Guid for ID?
Guid ensures each employee has a unique ID that is hard to guess, especially useful in distributed systems.
✅ Step 7: Create the Migration and Update Database
Once your model and DbContext are ready, you need to tell EF Core to generate the SQL scripts for creating the database.
Go to Tools > NuGet Package Manager > Package Manager Console, and run:
Add-Migration "initial migration"
Update-Database
📘 Explanation:
•Add-Migration InitialCreate: EF Core checks your models and prepares a migration file with all necessary SQL to create the tables.
•Update-Database: Applies migration and actually creates the database and tables in SQL Server.
•This is only needed when using the Code First approach
✅ Step 8: Create DTO Classes
Now let’s create Data Transfer Objects (DTOs). These are simple classes used to send and receive data without exposing your actual database models.
1.Right-click on the Models folder > Add > Class> Name it AddEmployeeDto.cs:
Then add this code:
2.Right-click again on the Models folder > Add > Class > Name it UpdateEmployeeDto.cs:
Then add this code:
📊 Why use DTOs?
•They prevent over-posting and reduce security risks.
•Keep your database entities separate from what the client sees or sends.
•Make your API cleaner, safer, and more maintainable.
🧠 For example, you may not want to expose an internal field like Id or CreatedDate to the client — DTOs let you control exactly what goes in and out.
DTOs separate the API layer from the database. They also help validate and protect incoming data from unwanted fields.
✅ Step 9: Create the Controller
- Right-click on the Controllers folder > Add > Controller > Choose API Controller - Empty
- Name it EmployeesController.cs At the top of the controller:
[Route("api/[controller]")]
[ApiController] // Helps with automatic validation and binding
Then add:
private readonly ApplicationDbContext dbContext;
public EmployeesController(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}
✅ Step 10: Add CRUD Endpoints
Each of the following methods allows us to interact with the Employees table in our database. Let's explore what each method does and how it works.
👁 Read All Employees:
This method fetches all employees from the database using ToList():
[HttpGet]
Public IActionResult GetEmployees()
{
return Ok(dbContext.Employees.ToList());
}
📘 Explanation:
•[HttpGet] defines this as a GET method.
•dbContext.Employees.ToList() retrieves all records from the Employees table.
•Ok(...) sends back an HTTP 200 response with the list.
🔎 Read Single Employee:
•This method fetches a specific employee by their ID:
[HttpGet("{id:guid}")]
public IActionResult GetEmployeeById(Guid id)
{
var employee = dbContext.Employees.Find(id);
return employee == null ? NotFound() : Ok(employee);
}
📘 Explanation:
•{id:guid} tells the API to expect a GUID in the route.
•Find(id) looks for a record matching the ID.
•If not found, it returns 404; else, it returns the employee.
➕ Create New Employee:
•This method creates a new employee using data from the DTO:
[HttpPost]
public IActionResult AddEmployee(AddEmployeeDto dto)
{
var employee = new Employee
{
Name = dto.Name,
Email = dto.Email,
Phone = dto.Phone,
Salary = dto.Salary
};
dbContext.Employees.Add(employee);
dbContext.SaveChanges();
return Ok(employee);
}
📘 Explanation:
•[HttpPost] marks this as a POST endpoint.
•A new Employee object is created from the DTO.
•Add(...) adds it to the DbSet.
•SaveChanges() commits it to the database.
✏️ Update Employee:
•This method updates an existing employee's information:
[HttpPut("{id:guid}")]
public IActionResult UpdateEmployee(Guid id, UpdateEmolyeeDto dto)
{
var employee = dbContext.Employees.Find(id);
if (employee == null) return NotFound();
employee.Name = dto.Name;
employee.Email = dto.Email;
employee.Phone = dto.Phone;
employee.Salary = dto.Salary;
dbContext.SaveChanges();
return Ok(employee);
}
📘 Explanation:
•[HttpPut] marks this as an update request.
•First, we check if the employee exists.
•If found, update its fields and call SaveChanges() to persist the changes.
❌ Delete Employee:
This method deletes an employee by ID:
[HttpDelete("{id:guid}")]
public IActionResult DeleteEmployee(Guid id)
{
var employee = dbContext.Employees.Find(id);
if (employee == null) return NotFound();
dbContext.Employees.Remove(employee);
dbContext.SaveChanges();
return Ok(employee);
}
📘 Explanation:
•[HttpDelete] marks this as a delete method.
•Find(id) fetches the employee.
•Remove(...) marks the record for deletion.
•SaveChanges() applies the deletion in the database.
•Returns the deleted object for confirmation.
✅ Conclusion
Congratulations! 🎉 You just built a fully functional ASP.NET Core Web API using Entity Framework Core (Code First) and .NET 8.
You learned:
•What Web API, CRUD, and EF Core
•How to use DTOs for clean code
•How to set up a .NET 8 Web API project step-by-step
•How to create and connect to a SQL Server database
•How to build CRUD operations for Employee data
This is a perfect starting point for any beginner wanting to master backend development in ASP.NET.
Top comments (0)