Introduction
In the previous lessons, we prepared the API layer, built a WebApplicationFactory-based integration test host, and learned how to replace application dependencies in a test environment. In this lesson, we will establish a persistent data layer using Entity Framework Core and SQL Server. The goal is not simply to create a few tables. We also need to separate the responsibilities of the real application database and the test database, manage schema changes through migrations, and organize data access in a testable way.
We will use the product data in our order application as the example. We will create a Product entity, an ApplicationDbContext, Fluent API configuration, and a repository implementation. We will then create and apply a SQL Server migration. In the next lesson, this infrastructure will be used in real API integration tests.
Core principle: When integration tests involve the database, they should use the same database provider as the application whenever practical. This exposes SQL Server-specific query behavior and constraints instead of hiding them behind a different provider.
1. Responsibilities of application and test databases
The development or production database stores real application data. The test database exists to make tests isolated, repeatable, and safe. Test code must never accidentally modify real users, orders, or other business records, so the connection settings must be separate.
| Area | Application database | Test database |
|---|---|---|
| Purpose | Real application data | Temporary data for a test scenario |
| Lifetime | Long-lived | Per test class or test run |
| Connection settings | Development, staging, or production configuration | Test configuration with a separate database name |
| Cleanup | Controlled migrations and operations | Transactions, recreation, or explicit cleanup |
Using the development connection string from a test project is a serious mistake. Instead, use a separate database name such as ShopApp_Test_<run-id>. When a shared SQL Server instance is used, the name should be unique if tests can run in parallel.
2. Creating the entity model
Let us define the product model in the domain layer. The domain object should not depend on the database. EF Core-specific mapping decisions will be placed in a separate configuration class.
namespace ShopApp.Domain.Products; public sealed class Product { private Product() { } public Product(string name, decimal price, int stockQuantity) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Product name is required.", nameof(name)); if (price < 0) throw new ArgumentOutOfRangeException(nameof(price)); if (stockQuantity < 0) throw new ArgumentOutOfRangeException(nameof(stockQuantity)); Id = Guid.NewGuid(); Name = name.Trim(); Price = price; StockQuantity = stockQuantity; } public Guid Id { get; private set; } public string Name { get; private set; } = string.Empty; public decimal Price { get; private set; } public int StockQuantity { get; private set; } public DateTime CreatedUtc { get; private set; } }
The private parameterless constructor allows EF Core to materialize an entity from the database. Business rules remain protected through the public constructor or domain methods. This prevents the persistence model from making invalid products easy to create in application code.
3. DbContext and entity configuration
First, define the interface required by the application layer:
public interface IProductRepository { Task<Product?> GetByIdAsync(Guid id, CancellationToken cancellationToken); Task<IReadOnlyList<Product>> GetAvailableAsync(CancellationToken cancellationToken); Task AddAsync(Product product, CancellationToken cancellationToken); Task SaveChangesAsync(CancellationToken cancellationToken); }
The infrastructure project can contain the DbContext and Fluent API configuration:
using Microsoft.EntityFrameworkCore; using ShopApp.Domain.Products; public sealed class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Product> Products => Set<Product>(); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(typeof(ApplicationDbContext).Assembly); } } public sealed class ProductConfiguration : IEntityTypeConfiguration<Product> { public void Configure(EntityTypeBuilder<Product> builder) { builder.ToTable("Products"); builder.HasKey(product => product.Id); builder.Property(product => product.Name) .HasMaxLength(200) .IsRequired(); builder.Property(product => product.Price) .HasPrecision(18, 2) .IsRequired(); builder.Property(product => product.StockQuantity) .IsRequired(); builder.Property(product => product.CreatedUtc) .IsRequired(); builder.HasIndex(product => product.Name); } }
This separation keeps table names, column lengths, precision, and indexes out of the entity class. HasPrecision(18, 2) explicitly maps the monetary value to an appropriate SQL Server decimal representation instead of relying on an ambiguous default.
4. Adding and configuring the SQL Server provider
Add the SQL Server provider and design-time tools to the infrastructure project:
dotnet add src/ShopApp.Infrastructure package Microsoft.EntityFrameworkCore.SqlServer dotnet add src/ShopApp.Infrastructure package Microsoft.EntityFrameworkCore.Design dotnet tool install --global dotnet-ef
Register the context through dependency injection in Program.cs:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( builder.Configuration.GetConnectionString("ApplicationDatabase"), sqlOptions => sqlOptions.EnableRetryOnFailure())); builder.Services.AddScoped<IProductRepository, ProductRepository>();
For local development, the connection string can be stored in appsettings.Development.json:
{ "ConnectionStrings": { "ApplicationDatabase": "Server=(localdb)\\MSSQLLocalDB;Database=ShopApp_Development;Trusted_Connection=True;TrustServerCertificate=True;" } }
Secrets and production connection strings should not be committed to source control. Use environment variables, a secret store, or the secure configuration mechanism provided by the deployment platform.
5. Implementing the repository
A repository reduces the need for application services to depend directly on DbSet details. However, a repository should express actual application data requirements rather than becoming an unnecessary wrapper around generic CRUD operations.
public sealed class ProductRepository : IProductRepository { private readonly ApplicationDbContext _dbContext; public ProductRepository(ApplicationDbContext dbContext) { _dbContext = dbContext; } public Task<Product?> GetByIdAsync( Guid id, CancellationToken cancellationToken) { return _dbContext.Products .SingleOrDefaultAsync(product => product.Id == id, cancellationToken); } public async Task<IReadOnlyList<Product>> GetAvailableAsync( CancellationToken cancellationToken) { return await _dbContext.Products .Where(product => product.StockQuantity > 0) .OrderBy(product => product.Name) .AsNoTracking() .ToListAsync(cancellationToken); } public Task AddAsync(Product product, CancellationToken cancellationToken) { return _dbContext.Products.AddAsync(product, cancellationToken).AsTask(); } public Task SaveChangesAsync(CancellationToken cancellationToken) { return _dbContext.SaveChangesAsync(cancellationToken); } }
AsNoTracking is useful for read-only queries because EF Core does not need to track changes for the returned entities. If an entity will be modified and saved using the same context, tracking behavior must be selected intentionally.
6. Creating and applying a migration
Create a migration to synchronize the model and database schema:
dotnet ef migrations add InitialProductSchema \ --project src/ShopApp.Infrastructure \ --startup-project src/ShopApp.Api \ --output-dir Persistence/Migrations
Apply it to the local development database:
dotnet ef database update \ --project src/ShopApp.Infrastructure \ --startup-project src/ShopApp.Api
A migration usually contains Up and Down methods together with a model snapshot. Up represents the forward schema change, while Down describes how to reverse it. Applied migrations are tracked in EF Core’s migrations history table.
Calling automatic migration logic every time the application starts can be risky in production, particularly when several application instances are running. A controlled deployment step, generated SQL scripts, or a dedicated migration job is generally more appropriate.
7. Connecting tests to a separate database
The test project should replace the application database registration. The following factory removes the original ApplicationDbContext registration and adds a separate SQL Server connection:
public sealed class SqlServerTestWebApplicationFactory : WebApplicationFactory<Program> { private readonly string _databaseName = $"ShopApp_Test_{Guid.NewGuid():N}"; protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Testing"); builder.ConfigureServices(services => { var descriptor = services.SingleOrDefault(service => service.ServiceType == typeof(DbContextOptions<ApplicationDbContext>)); if (descriptor is not null) services.Remove(descriptor); var connectionString = $"Server=(localdb)\\MSSQLLocalDB;Database={_databaseName};" + "Trusted_Connection=True;TrustServerCertificate=True;"; services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); }); } }
This factory never touches the application development database. Each factory instance gets a unique database name. A separate helper can apply migrations before the tests begin and delete the database after the test run. These responsibilities belong to the test infrastructure, not to production application code.
Common mistakes
- Using the production connection in tests: This creates data-loss and security risks. Separate the test connection explicitly.
- Mixing EnsureCreated and migrations: EnsureCreated bypasses migration history and is not a replacement for migration-based schema management.
- Creating meaningless repositories for every entity: Repository interfaces should express use-case-oriented data access instead of only generic Get, Add, and Update methods.
- Treating SQLite or the in-memory provider as an exact SQL Server replacement: Providers can differ in query translation, constraints, and date or decimal behavior.
- Committing migrations without reviewing them: Dropped columns, data movement, and index changes can cause data loss.
- Keeping a DbContext alive too long: A scoped lifetime is appropriate for web requests, and the same context should not be shared across unrelated tests.
Short practice exercise
- Create a new Category entity and associate it with Product.
- Write a Fluent API configuration with a maximum name length and a unique index.
- Add the relationship to ApplicationDbContext.
- Create a migration named AddCategories with the equivalent dotnet ef command.
- Apply it to the development database and inspect the generated foreign key and indexes in SQL Server.
- Verify that the test factory does not use the development database. Log the database name during the test, but never log a password or complete secret-bearing connection string.
Conclusion
In this lesson, we registered the SQL Server provider with ASP.NET Core dependency injection and built the entity, DbContext, Fluent API configuration, and repository layers. We made schema changes traceable through migrations and designed a separate test connection so integration tests cannot modify the real application database.
The next step is to write API integration tests against this real SQL Server infrastructure. Those tests will validate not only controller and service behavior, but also query translation, constraints, migrations, and data persistence together.
Sources
- https://learn.microsoft.com/ef/core/providers/sql-server/
- https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
- https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/managing
- https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/migrations?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/ef/core/testing/
- https://learn.microsoft.com/en-us/ef/core/testing/choosing-a-testing-strategy