Introduction
In the previous lessons, we created the real ASP.NET Core Web API project, ran the application in a container, and prepared a multi-stage Dockerfile. In this lesson, we will build the data access layer that the application still needs. The goal is to create Product and Category entities, model their relationship, add an Entity Framework Core DbContext, and prepare CRUD endpoints that work with SQL Server.
We will not create the database schema with migrations in this lesson; migrations are covered in a later lesson. Instead, we will configure the application correctly for the SQL Server provider and make the API ready for database access. Because the application will eventually run in containers, we will also keep in mind that a Docker network name or service name—not localhost—will be used when the API connects to a SQL Server container.
1. Planning the project structure
Assume that the project is named CatalogApi. By the end of the lesson, it will have a structure similar to this:
CatalogApi/ ├── Controllers/ │ └── ProductsController.cs ├── Data/ │ └── CatalogDbContext.cs ├── Models/ │ ├── Category.cs │ └── Product.cs ├── Contracts/ │ └── ProductRequests.cs ├── appsettings.json └── Program.cs
This structure is not mandatory, but separating entities, database context, and HTTP endpoints makes the code easier to understand and maintain. Entity classes represent objects mapped to database tables, the DbContext represents the database session, and the controller handles HTTP requests.
2. Adding the SQL Server provider
Entity Framework Core uses database provider packages to work with different database systems. The official provider for SQL Server is Microsoft.EntityFrameworkCore.SqlServer. Its major version should match the EF Core version targeted by the application. For example, if the application uses EF Core 9, select a 9.x SQL Server provider.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet restore
If you plan to run migrations later, you can also add the design-time tools. Since this lesson focuses on the provider and API data layer rather than migration execution, we will keep the package setup focused. If the provider package is missing, the UseSqlServer extension method will not be available and the project will fail to compile.
3. Creating the Category and Product entities
Our first entity is the category. A category can contain multiple products, so the relationship will be modeled as one-to-many.
namespace CatalogApi.Models; public class Category { public int Id { get; set; } public string Name { get; set; } = string.Empty; public ICollection<Product> Products { get; set; } = new List<Product>(); }
Initializing Products with an empty collection reduces the need for null checks on newly created category objects. Now add the product entity:
namespace CatalogApi.Models; public class Product { public int Id { get; set; } public string Name { get; set; } = string.Empty; public string Description { get; set; } = string.Empty; public decimal Price { get; set; } public int StockQuantity { get; set; } public int CategoryId { get; set; } public Category? Category { get; set; } }
CategoryId is the foreign key. The Category navigation property allows a product to reference its category. The decimal type is more appropriate than double for monetary values, although it is still good practice to define the database precision and scale explicitly.
4. Configuring the DbContext
The DbContext connects entity types to database tables and executes queries. Create Data/CatalogDbContext.cs:
using CatalogApi.Models; using Microsoft.EntityFrameworkCore; namespace CatalogApi.Data; public class CatalogDbContext : DbContext { public CatalogDbContext(DbContextOptions<CatalogDbContext> options) : base(options) { } public DbSet<Product> Products => Set<Product>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Category>() .Property(category => category.Name) .HasMaxLength(100) .IsRequired(); modelBuilder.Entity<Product>() .Property(product => product.Name) .HasMaxLength(200) .IsRequired(); modelBuilder.Entity<Product>() .Property(product => product.Price) .HasPrecision(18, 2); modelBuilder.Entity<Product>() .HasOne(product => product.Category) .WithMany(category => category.Products) .HasForeignKey(product => product.CategoryId) .OnDelete(DeleteBehavior.Restrict); } }
DeleteBehavior.Restrict prevents a category from being deleted while products still reference it. This avoids accidentally deleting related products. Cascade delete is another option, but for a catalog application it is safer to choose the delete behavior explicitly.
5. Configuration and dependency injection
For now, we will show the connection string in appsettings.json. In a real container deployment, passwords and other secrets should be supplied through environment variables or a secret-management mechanism; that topic will be expanded in later lessons.
{ "ConnectionStrings": { "CatalogDb": "Server=localhost,1433;Database=CatalogDb;User Id=sa;Password=YourStrong!Passw0rd;TrustServerCertificate=True;" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } } }
When the application runs directly on your computer, localhost may be correct. When the API also runs inside Docker, it must use the SQL Server container's name on the shared Docker network instead of localhost. The networking lesson will examine this in detail.
Register the provider and context in Program.cs:
using CatalogApi.Data; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var connectionString = builder.Configuration .GetConnectionString("CatalogDb") ?? throw new InvalidOperationException( "CatalogDb connection string was not found."); builder.Services.AddDbContext<CatalogDbContext>(options => options.UseSqlServer(connectionString)); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.MapControllers(); app.Run();
ASP.NET Core supplies a context registered with AddDbContext to controllers through constructor injection. The default lifetime is one context instance per request. Do not share the same DbContext instance across parallel operations because a context is not thread-safe.
6. Request models and the controller
Using request models instead of binding HTTP request bodies directly to entities allows us to control which fields clients can change. Create Contracts/ProductRequests.cs:
using System.ComponentModel.DataAnnotations; namespace CatalogApi.Contracts; public record ProductCreateRequest( [Required, MaxLength(200)] string Name, [MaxLength(1000)] string? Description, [Range(0.01, 1000000)] decimal Price, [Range(0, int.MaxValue)] int StockQuantity, [Range(1, int.MaxValue)] int CategoryId); public record ProductUpdateRequest( [Required, MaxLength(200)] string Name, [MaxLength(1000)] string? Description, [Range(0.01, 1000000)] decimal Price, [Range(0, int.MaxValue)] int StockQuantity, [Range(1, int.MaxValue)] int CategoryId);
Now add basic listing, detail, creation, update, and deletion operations to the controller.
using CatalogApi.Contracts; using CatalogApi.Data; using CatalogApi.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace CatalogApi.Controllers; [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly CatalogDbContext _db; public ProductsController(CatalogDbContext db) { _db = db; } [HttpGet] public async Task<ActionResult<IReadOnlyList<Product>>> GetAll() { var products = await _db.Products .AsNoTracking() .Include(product => product.Category) .OrderBy(product => product.Name) .ToListAsync(); return Ok(products); } [HttpGet("{id:int}")] public async Task<ActionResult<Product>> GetById(int id) { var product = await _db.Products .AsNoTracking() .Include(item => item.Category) .FirstOrDefaultAsync(item => item.Id == id); return product is null ? NotFound() : Ok(product); } [HttpPost] public async Task<ActionResult<Product>> Create(ProductCreateRequest request) { var categoryExists = await _db.Categories .AnyAsync(category => category.Id == request.CategoryId); if (!categoryExists) { return BadRequest("The specified category does not exist."); } var product = new Product { Name = request.Name, Description = request.Description ?? string.Empty, Price = request.Price, StockQuantity = request.StockQuantity, CategoryId = request.CategoryId }; _db.Products.Add(product); await _db.SaveChangesAsync(); return CreatedAtAction(nameof(GetById), new { id = product.Id }, product); } [HttpPut("{id:int}")] public async Task<IActionResult> Update( int id, ProductUpdateRequest request) { var product = await _db.Products.FindAsync(id); if (product is null) { return NotFound(); } var categoryExists = await _db.Categories .AnyAsync(category => category.Id == request.CategoryId); if (!categoryExists) { return BadRequest("The specified category does not exist."); } product.Name = request.Name; product.Description = request.Description ?? string.Empty; product.Price = request.Price; product.StockQuantity = request.StockQuantity; product.CategoryId = request.CategoryId; await _db.SaveChangesAsync(); return NoContent(); } [HttpDelete("{id:int}")] public async Task<IActionResult> Delete(int id) { var product = await _db.Products.FindAsync(id); if (product is null) { return NotFound(); } _db.Products.Remove(product); await _db.SaveChangesAsync(); return NoContent(); } }
AsNoTracking disables change tracking for read-only queries and can reduce unnecessary overhead. Tracking is needed for create and update operations. Include loads the related category together with each product.
7. Running and testing the application
Build and run the project:
dotnet build dotnet run
Use Swagger or another HTTP client to try the following operations:
GET /api/products GET /api/products/1 POST /api/products PUT /api/products/1 DELETE /api/products/1
Example JSON for creating a product:
{ "name": "Mechanical Keyboard", "description": "Compact USB keyboard", "price": 89.90, "stockQuantity": 25, "categoryId": 1 }
If the database does not yet contain tables or categories, the requests may not return the expected results. That is normal. Creating tables and initial data will be handled later through migrations and seed operations.
Common mistakes
- Using incompatible package versions: Keep the major version of the EF Core provider aligned with the target framework and the other EF Core packages.
- UseSqlServer is unavailable: Confirm that the SQL Server provider is installed and that using Microsoft.EntityFrameworkCore; is present.
- Using localhost inside a container: From the API container, localhost refers to the API container itself, not the SQL Server container.
- Skipping foreign-key validation: An invalid CategoryId can cause data-integrity errors. Check that the category exists before creating or updating a product.
- Binding entities directly: Restrict client-controlled fields by using request models and validation attributes.
- Expecting the context to create tables: Defining a DbContext does not automatically create the schema. A migration or another controlled database deployment step is required.
Short practice exercise
Task: Add an IsActive boolean property to the product catalog. Return only active products from the listing endpoint and include the property in the update request model.
- Add public bool IsActive { get; set; } = true; to the Product class.
- Add a bool IsActive parameter to ProductUpdateRequest.
- Add Where(product => product.IsActive) to the GetAll query.
- Build the application and verify the behavior of active and inactive products through Swagger.
Conclusion
In this lesson, we extended the ASP.NET Core API with a real data model. We created the Product and Category entities, defined their one-to-many relationship with the Fluent API, added the SQL Server provider, and registered CatalogDbContext with dependency injection. We also prepared asynchronous controller actions for listing, retrieving, creating, updating, and deleting products.
The application is now ready to connect to SQL Server. In the next stage, we will set up the SQL Server container securely and examine how connection information is supplied in a container environment. The entity model and context created here form the foundation for the migration, networking, and Docker Compose work that follows.
Sources
- https://learn.microsoft.com/en-us/ef/core/providers/sql-server/
- https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
- https://learn.microsoft.com/en-us/ef/core/providers/
- https://learn.microsoft.com/en-us/aspnet/core/web-api/
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/