In the previous sections, we implemented all four layers of Clean Architecture and configured Dependency Injection to connect the application components.
Now, we need to configure the database and create the required database tables.
ASP.NET Clean Architecture: Configure Database and Run Migrations
Getting Started
For our Employee Management Web API, we will use SQL Server with Entity Framework Core. We will configure the database connection, create the initial migration, and apply the migration to generate the database schema.
Let's complete this step by step.Step 1: Configure the SQL Server Connection String
First, open the appsettings.json file in the CleanArchitectureDemo.API project.
</> JSON
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost\\SQLEXPRESS;Database=CleanArchitectureDB;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
Here is what each connection string parameter represents:
- Server: SQL Server instance name
- Database: Name of the database
- Trusted_Connection: Uses Windows Authentication
- TrustServerCertificate: Trusts the SQL Server certificate without certificate validation
Note: Replace localhost\\SQLEXPRESS with your actual SQL Server instance name. If you are using LocalDB, you can use (localdb)\\MSSQLLocalDB.
Step 2: Verify the Entity Framework Core Configuration
Before running migrations, make sure that the Infrastructure Layer contains the ApplicationDbContext class. Where we have configured the Employee entity using the Entity Framework Core Fluent API.
This configuration defines the database schema without introducing database-specific dependencies into the Domain Layer. In the previous acrticle, i have mentioned this class with implementation, if you have not added then create the class and update the below code
</> C#
using CleanArchitectureDemo.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace CleanArchitectureDemo.Infrastructure.Data;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees => Set<Employee>();
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Employee>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100);
entity.Property(e => e.Email)
.IsRequired()
.HasMaxLength(150);
entity.Property(e => e.Salary)
.HasPrecision(18, 2);
});
}
}
Step 3: Install Entity Framework Core Tools
To create and apply database migrations, we need the Entity Framework Core command-line tools.
Open the Package Manager Console in Visual Studio: Tools → NuGet Package Manager → Package Manager Console
Execute the following command:</> powershell
Install-Package Microsoft.EntityFrameworkCore.Tools
Alternatively, install the .NET CLI tool. If it is already installed, update it to a version compatible with your Entity Framework Core packages
Make sure the versions of Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Design, Microsoft.EntityFrameworkCore.Tools, and dotnet-ef are compatible.
Step 4: Create the Initial Migration
Entity Framework Core migrations help us keep the database schema synchronized with our application's entity models.
Since our ApplicationDbContext is located in the Infrastructure project and our API project acts as the startup project, we need to specify both projects when creating migrations.
</> Bash
dotnet ef migrations add InitialCreate \
--project CleanArchitectureDemo.Infrastructure \
--startup-project CleanArchitectureDemo.API \
If you are using Windows PowerShell, you can also execute the command on a single line:
</> powershell
dotnet ef migrations add InitialCreate --project CleanArchitectureDemo.Infrastructure --startup-project CleanArchitectureDemo.API
This command performs the following operations:
- Identifies the
ApplicationDbContextin the Infrastructure project. - Uses the API project to obtain the application configuration and dependency injection setup.
- Compares the current entity model with the migration snapshot.
- Generates migration files containing the database schema changes.
After successfully creating the migration, your Infrastructure project should contain the following structure:
</> Plain Text
CleanArchitectureDemo.Infrastructure
│
├── Data
│ ├── Migrations
│ │ ├── 20261031000000_InitialCreate.cs
│ │ ├── 20261031000000_InitialCreate.Designer.cs
│ │ └── ApplicationDbContextModelSnapshot.cs
│ │
│ └── ApplicationDbContext.cs
│
├── Repositories
│ └── EmployeeRepository.cs
│
└── DependencyInjection.cs
The migration timestamp and generated filenames will differ in your project.
Step 5: Apply the Migration to SQL Server
After creating the migration, we need to apply it to SQL Server to create the database and its corresponding tables.
Execute the following command:</> powershell
dotnet ef database update --project CleanArchitectureDemo.Infrastructure --startup-project CleanArchitectureDemo.API
Entity Framework Core will:
- Connects to SQL Server using the configured connection string.
- Creates the
CleanArchitectureDBdatabase if it does not already exist. - Executes the migration scripts.
- Creates the
Employeestable. - Maintains the migration history in the
__EFMigrationsHistorytable.
Step 6: Verify the Database and Employees Table
Open SQL Server Management Studio (SSMS) and connect to your SQL Server instance.
Follow these steps:- Expand the Databases folder.
- Locate
CleanArchitectureDB. - Expand the Tables folder.
- Verify that the
dbo.Employeestable has been created. - Expand the table's Columns folder to verify the database schema.
You should see columns similar to the following:
| Column | Data Type | Description |
|---|---|---|
| Id | int | Primary key |
| Name | nvarchar(100) | Employee name |
| nvarchar(150) | Employee email | |
| Salary | decimal(18,2) | Employee salary |
You can also execute the following SQL query to verify the table:
</> SQL
USE CleanArchitectureDB;
SELECT * FROM Employees;
Initially, the table will be empty because we have not inserted any employee records yet.
Step 7: Understanding the Migration Workflow
Whenever we make changes to our Domain entities or database configuration, we can generate a new migration.
For example, if we add a new property called Department to the Employee entity, we can create another migration:
</> powershell
dotnet ef migrations add AddEmployeeDepartment --project CleanArchitectureDemo.Infrastructure --startup-project CleanArchitectureDemo.API
Then apply the changes:
</> powershell
dotnet ef database update --project CleanArchitectureDemo.Infrastructure --startup-project CleanArchitectureDemo.API
Entity Framework Core will generate the necessary database schema changes based on the updated model.
This approach allows us to manage database schema changes through version-controlled migration files.
Common Issues and Solutions| Issue | Possible Solution |
|---|---|
| Unable to create DbContext | Verify project references and dependency injection configuration. |
| SQL Server connection failed | Check the SQL Server instance name and connection string. |
| No DbContext found | Specify the Infrastructure project using --project. |
| Unable to create migration | Check EF Core package and tool version compatibility. |
| Database already exists | Check whether the migration has already been applied. |
Additional Note: If EF Core cannot create the DbContext using the API startup project, you may need to implement an IDesignTimeDbContextFactory<ApplicationDbContext> in the Infrastructure project to provide design-time configuration.
Summary
We have successfully configured SQL Server and created the database schema for our Employee Management Web API using Entity Framework Core.
In this section, we:- Configured the SQL Server connection string.
- Verified the Entity Framework Core DbContext.
- Installed Entity Framework Core tools.
- Created the initial database migration.
- Applied migrations to SQL Server.
- Verified the Employees table.
Our database is now ready to store employee information.
In the next section, we will Test the API Using Swagger and verify all five CRUD operations by creating, retrieving, updating, and deleting employee records.
Thanks