Introduction
In the previous lesson, we defined the service boundaries and data ownership rules for our solution. In this lesson, we will build our first real business service: the Catalog service. Catalog will be responsible for creating, listing, updating, and deleting products. Product data will be stored in the SQL Server database owned by this service; other services must not access the product tables directly.
In our application model, Catalog will be an independent ASP.NET Core Web API project, while its Catalog database will be represented by a SQL Server resource managed by the Aspire AppHost. This approach has two important consequences. First, the API accesses data only through its own application layer. Second, database connection details are not hard-coded into the service. Aspire supplies the required connection information through a resource reference when the application runs.
By the end of this lesson, we will have the following flow working:
- Define the product entity for the Catalog domain.
- Create an Entity Framework Core
DbContext. - Configure SQL Server access.
- Create a migration and generate the database schema.
- Use DTOs for requests and responses.
- Apply input validation rules.
- Implement CRUD endpoints.
- Connect the Catalog API to SQL Server through the Aspire AppHost.
1. The responsibility of the Catalog service
The Catalog service will be the single owner of product catalog data. Product name, description, price, category, and availability belong to this service. If the basket or order service needs product information, it must not connect directly to the Catalog database. Instead, it should use one of the HTTP or messaging-based communication patterns that we will study later.
We can begin with a simple product model. For the first version, an identifier, name, description, price, category, active status, and creation timestamp are sufficient:
public sealed class Product
{
public Guid Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public decimal Price { get; set; }
public string Category { get; set; } = string.Empty;
public bool IsActive { get; set; }
public DateTime CreatedAtUtc { get; set; }
}A Guid reduces the possibility of collisions when identifiers are generated independently by different services. Use decimal for monetary values; double can introduce rounding problems in financial calculations. Storing timestamps in UTC is safer for services that run on different machines and in different time zones.
2. The difference between an entity and a DTO
An entity represents the persistence model used by the database. A DTO represents data crossing the API boundary. Using one class for both may seem convenient at first, but it eventually couples clients to database details.
For example, clients should not be allowed to submit Id, CreatedAtUtc, or IsActive when creating a product. These values should be controlled by the server. Therefore, we will define separate DTOs for creation, updates, and responses:
public sealed record CreateProductRequest(
string Name,
string Description,
decimal Price,
string Category);
public sealed record UpdateProductRequest(
string Name,
string Description,
decimal Price,
string Category,
bool IsActive);
public sealed record ProductResponse(
Guid Id,
string Name,
string Description,
decimal Price,
string Category,
bool IsActive,
DateTime CreatedAtUtc);DTOs are not only a security mechanism. They separate the API contract from the database schema, make it easier to evolve entities without breaking clients, and clearly define which fields are writable.
3. Configuring the DbContext and model
The main Entity Framework Core component between the application and SQL Server is the DbContext. Let us create a dedicated context for Catalog:
using Microsoft.EntityFrameworkCore;
public sealed class CatalogDbContext(DbContextOptions<CatalogDbContext> options)
: DbContext(options)
{
public DbSet<Product> Products => Set<Product>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var product = modelBuilder.Entity<Product>();
product.ToTable("Products");
product.HasKey(x => x.Id);
product.Property(x => x.Name)
.HasMaxLength(200)
.IsRequired();
product.Property(x => x.Description)
.HasMaxLength(2000)
.IsRequired();
product.Property(x => x.Category)
.HasMaxLength(100)
.IsRequired();
product.Property(x => x.Price)
.HasPrecision(18, 2)
.IsRequired();
product.Property(x => x.CreatedAtUtc)
.IsRequired();
}
}The Fluent API explicitly defines the table name, required fields, maximum lengths, and price precision. These rules are represented not only in the application model but also in the database schema generated by the migration.
4. Adding SQL Server access
Add the SQL Server EF Core provider and design-time tools to the Catalog API project:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.DesignIn Program.cs, we will read the connection string named catalogdb. This name must match the database resource created in the Aspire AppHost:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddOpenApi();
builder.Services.AddDbContext<CatalogDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("catalogdb"),
sql => sql.EnableRetryOnFailure()));
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.MapControllers();
app.Run();EnableRetryOnFailure allows EF Core to retry certain operations after transient connection failures. It does not fix permanent failures, but it is useful when the SQL Server container is still starting or a short-lived network problem occurs.
5. Defining SQL Server in the Aspire AppHost
In the AppHost, we will express the dependency between SQL Server and the Catalog API in code:
var builder = DistributedApplication.CreateBuilder(args);
var catalogDatabase = builder
.AddSqlServer("sql")
.AddDatabase("catalogdb");
builder.AddProject<Projects.CatalogApi>("catalog-api")
.WithReference(catalogDatabase)
.WaitFor(catalogDatabase);
builder.Build().Run();AddSqlServer("sql") defines the SQL Server resource, while AddDatabase("catalogdb") defines the database on that server. WithReference supplies the database connection information to the API. Therefore, the connection string does not need to be hard-coded in appsettings.json. WaitFor helps prevent the API from starting before the database resource is ready.
The AppHost project must reference the appropriate hosting package:
dotnet add package Aspire.Hosting.SqlServerThis configuration allows the SQL Server container to run in the local development environment and makes the resource visible through the Aspire dashboard. If database data must survive container restarts, persistent volume or lifetime options can be configured according to the Aspire APIs supported by the project and environment.
6. Creating a migration
Once the entity model is ready, create the first migration:
dotnet ef migrations add InitialCatalogSchema \
--project CatalogApi \
--startup-project CatalogApi
dotnet ef database update \
--project CatalogApi \
--startup-project CatalogApiMigration files represent changes to the model and should be stored with the source code. The database update command brings the development database to the latest migration. Instead of manually editing migration files, change the model and generate a new migration.
Automatically running migrations during application startup is not always appropriate in production. Multiple instances may attempt to update the schema at the same time, and some schema changes can take a long time. For production deployments, a migration bundle or a reviewed SQL script may provide better control.
7. Validation rules
We should validate data received from clients before processing it. Data annotations can be added to the DTO:
using System.ComponentModel.DataAnnotations;
public sealed record CreateProductRequest(
[property: Required, StringLength(200, MinimumLength = 2)]
string Name,
[property: StringLength(2000)]
string Description,
[property: Range(typeof(decimal), "0.01", "999999999.99")]
decimal Price,
[property: Required, StringLength(100)]
string Category);With a controller-based API, the [ApiController] attribute can automatically produce a 400 response for model validation failures. Validation does not replace database constraints. If the domain requires unique product names or additional business rules, those rules must also be implemented explicitly.
8. The CRUD controller
Now create the basic endpoints:
[ApiController]
[Route("api/products")]
public sealed class ProductsController(CatalogDbContext db) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<IReadOnlyList<ProductResponse>>> GetAll(
CancellationToken cancellationToken)
{
var products = await db.Products
.AsNoTracking()
.OrderBy(x => x.Name)
.Select(x => new ProductResponse(
x.Id,
x.Name,
x.Description,
x.Price,
x.Category,
x.IsActive,
x.CreatedAtUtc))
.ToListAsync(cancellationToken);
return Ok(products);
}
[HttpGet("{id:guid}")]
public async Task<ActionResult<ProductResponse>> GetById(
Guid id,
CancellationToken cancellationToken)
{
var product = await db.Products
.AsNoTracking()
.Where(x => x.Id == id)
.Select(x => new ProductResponse(
x.Id,
x.Name,
x.Description,
x.Price,
x.Category,
x.IsActive,
x.CreatedAtUtc))
.SingleOrDefaultAsync(cancellationToken);
return product is null ? NotFound() : Ok(product);
}
[HttpPost]
public async Task<ActionResult<ProductResponse>> Create(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var product = new Product
{
Id = Guid.NewGuid(),
Name = request.Name.Trim(),
Description = request.Description.Trim(),
Price = request.Price,
Category = request.Category.Trim(),
IsActive = true,
CreatedAtUtc = DateTime.UtcNow
};
db.Products.Add(product);
await db.SaveChangesAsync(cancellationToken);
var response = new ProductResponse(
product.Id,
product.Name,
product.Description,
product.Price,
product.Category,
product.IsActive,
product.CreatedAtUtc);
return CreatedAtAction(nameof(GetById), new { id = product.Id }, response);
}
[HttpPut("{id:guid}")]
public async Task<IActionResult> Update(
Guid id,
UpdateProductRequest request,
CancellationToken cancellationToken)
{
var product = await db.Products
.SingleOrDefaultAsync(x => x.Id == id, cancellationToken);
if (product is null)
{
return NotFound();
}
product.Name = request.Name.Trim();
product.Description = request.Description.Trim();
product.Price = request.Price;
product.Category = request.Category.Trim();
product.IsActive = request.IsActive;
await db.SaveChangesAsync(cancellationToken);
return NoContent();
}
[HttpDelete("{id:guid}")]
public async Task<IActionResult> Delete(
Guid id,
CancellationToken cancellationToken)
{
var product = await db.Products
.SingleOrDefaultAsync(x => x.Id == id, cancellationToken);
if (product is null)
{
return NotFound();
}
db.Products.Remove(product);
await db.SaveChangesAsync(cancellationToken);
return NoContent();
}
}Using AsNoTracking for read-only queries prevents EF Core from tracking entities that will not be modified. Projecting directly to ProductResponse also prevents unnecessary columns and persistence details from leaking into the API response.
9. Common mistakes
- Using the entity as the request model: Clients may modify fields that should be controlled by the server.
- Hard-coding the connection string: Environment-specific values should come from the AppHost, secrets, or environment variables.
- Tracking every query: Read-only queries can incur unnecessary memory and processing costs.
- Ignoring migration files in source control: Other developers and deployment systems cannot reproduce the same schema.
- Confusing 404 and 400: An invalid request is 400, while a missing product is 404.
- Using floating-point types for prices: Use
decimaland define explicit precision. - Ignoring deletion semantics: If orders reference products, deactivation with
IsActivemay be safer than physical deletion. - Running production migrations on every startup: Schema changes should be handled as a controlled deployment step.
10. Short practice exercise
Complete the following exercise:
- Add a
Skuproperty to theProductentity and configure a maximum length of 50 characters. - Add a required-value validation rule for
Sku. - Create a new
AddSkuToProductmigration. - Include SKU in the GET response.
- Prevent a second product with the same SKU by defining a unique database index.
- Verify successful creation and duplicate-SKU behavior with a unit or integration test.
An example unique-index configuration is:
product.HasIndex(x => x.Sku)
.IsUnique();Conclusion
In this lesson, we built the Catalog service with a real data-access layer. We separated entities from DTOs, created an EF Core DbContext, obtained the SQL Server connection through an Aspire resource reference, generated a migration, and implemented validated CRUD endpoints.
This is the foundation of the service that we will extend in later lessons. When we add health checks, centralized error handling, service discovery, caching, messaging, and distributed tracing, the core responsibility of the Catalog API will remain the same; only its connections and operating conditions will become richer. The key principle is simple: Catalog owns catalog data, and that ownership must be protected both in the code structure and in the database access model.
Sources
- https://learn.microsoft.com/en-us/ef/core/providers/sql-server/
- https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/validation?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/app-host-overview
- https://learn.microsoft.com/en-us/dotnet/aspire/get-started/add-aspire-existing-app