Introduction
In the previous lesson, we focused on developing the Catalog service within its own API boundary. This lesson applies the same principle to the Order and Inventory services. More importantly, we will implement a central microservice rule: each service owns its domain data. The Order service owns orders, order lines, and order status. The Inventory service owns stock quantities, reservations, and stock movements.
The two services may use the same product identifier, but they must not directly access each other’s databases. Order must not query Inventory tables, and Inventory must not add foreign keys to Order tables. Their relationship will be expressed through API contracts or, in later lessons, messaging and integration events.
This design may appear to require more code and more databases. In return, it allows services to be deployed independently, schemas to evolve separately, and teams to change their own models without coordinating every database change with the entire application.
Learning objectives
- Create independent domain models for the Order and Inventory services.
- Configure a separate
DbContextand database for each service. - Define two SQL Server database resources in the Aspire AppHost.
- Run EF Core migrations per service.
- Explain the difference between a local transaction and a distributed transaction.
- Understand why services should not query each other’s tables directly.
1. Clarifying data ownership
Before designing tables, write down which service owns each piece of data.
| Service | Owned data | Information exposed to other services |
|---|---|---|
| Order | Orders, OrderItems, OrderStatus | Order summary and status |
| Inventory | StockItems, StockReservations, StockMovements | Stock availability and reservation result |
| Catalog | Products, Categories | Product name, price, and catalog state |
An order line may contain a ProductId. This does not mean that the Order database should create a foreign key to a Product table. The value represents the product selected when the order was created. If the product name or current price is required, the Order service can call Catalog or store a local snapshot received through an integration event.
2. The Order data layer
A simple structure can keep the Order domain and persistence concerns clear:
OrderService/
Domain/
Order.cs
OrderItem.cs
Infrastructure/
OrderDbContext.cs
Program.csExample domain classes:
namespace OrderService.Domain;
public sealed class Order
{
public Guid Id { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public string Status { get; set; } = "Pending";
public List<OrderItem> Items { get; set; } = [];
}
public sealed class OrderItem
{
public int Id { get; set; }
public Guid OrderId { get; set; }
public Guid ProductId { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
}The UnitPrice property is deliberate. If the Catalog service changes a product price, an existing order must not change retroactively. The price used when the order was created is therefore stored as Order-owned data.
Configure the context as follows:
using Microsoft.EntityFrameworkCore;
using OrderService.Domain;
namespace OrderService.Infrastructure;
public sealed class OrderDbContext(DbContextOptions<OrderDbContext> options)
: DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
public DbSet<OrderItem> OrderItems => Set<OrderItem>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.Status).HasMaxLength(32).IsRequired();
entity.HasMany(x => x.Items)
.WithOne()
.HasForeignKey(x => x.OrderId)
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<OrderItem>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.UnitPrice).HasPrecision(18, 2);
entity.HasIndex(x => new { x.OrderId, x.ProductId });
});
}
}Use the connection string name provided by Aspire in Program.cs:
builder.AddServiceDefaults();
builder.Services.AddDbContext<OrderDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("orderdb")));
var app = builder.Build();
app.MapDefaultEndpoints();
app.MapGet("/orders/{id:guid}", async (Guid id, OrderDbContext db) =>
await db.Orders.Include(x => x.Items).SingleOrDefaultAsync(x => x.Id == id));
app.Run();3. The Inventory data layer
The Inventory model does not recreate the Product entity. It contains information required for stock management.
namespace InventoryService.Domain;
public sealed class StockItem
{
public Guid ProductId { get; set; }
public int AvailableQuantity { get; set; }
public int ReservedQuantity { get; set; }
public byte[] Version { get; set; } = [];
}
public sealed class StockReservation
{
public Guid Id { get; set; }
public Guid ProductId { get; set; }
public Guid OrderId { get; set; }
public int Quantity { get; set; }
public string Status { get; set; } = "Reserved";
public DateTimeOffset CreatedAt { get; set; }
}The Inventory context is completely independent from the Order context:
using InventoryService.Domain;
using Microsoft.EntityFrameworkCore;
namespace InventoryService.Infrastructure;
public sealed class InventoryDbContext(DbContextOptions<InventoryDbContext> options)
: DbContext(options)
{
public DbSet<StockItem> StockItems => Set<StockItem>();
public DbSet<StockReservation> StockReservations => Set<StockReservation>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StockItem>(entity =>
{
entity.HasKey(x => x.ProductId);
entity.Property(x => x.Version).IsRowVersion();
});
modelBuilder.Entity<StockReservation>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.Status).HasMaxLength(32).IsRequired();
entity.HasIndex(x => new { x.OrderId, x.ProductId });
});
}
}The Version property can support optimistic concurrency. If two requests update the same stock record at the same time, EF Core can detect that the version has changed and reduce the risk of a lost update.
4. Defining two databases in the Aspire AppHost
Now add a SQL Server resource and two independent databases to the AppHost. Both databases may run inside the same SQL Server container during development. The important rule is that each service receives only its own connection string.
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql")
.WithDataVolume();
var orderDb = sql.AddDatabase("orderdb");
var inventoryDb = sql.AddDatabase("inventorydb");
var order = builder.AddProject<Projects.OrderService>("order")
.WithReference(orderDb)
.WaitFor(orderDb);
var inventory = builder.AddProject<Projects.InventoryService>("inventory")
.WithReference(inventoryDb)
.WaitFor(inventoryDb);
builder.Build().Run();WithReference(orderDb) gives the Order service only the orderdb connection details. The Inventory service receives only inventorydb. This explicit dependency graph makes accidental cross-service database access less likely.
5. Running migrations per service
Create a separate migration set for each context:
dotnet ef migrations add InitialOrderSchema \
--project src/OrderService \
--startup-project src/OrderService
dotnet ef migrations add InitialInventorySchema \
--project src/InventoryService \
--startup-project src/InventoryServiceMigrations must be applied with the correct connection string. In development, this can be handled by a controlled startup task or a dedicated migration worker. In production, automatically applying migrations during application startup requires care because multiple service instances might attempt the same operation concurrently.
6. Understanding transaction boundaries
The Order service can save an order and its lines in one local transaction:
await using var transaction = await db.Database.BeginTransactionAsync();
var order = new Order
{
Id = request.OrderId,
CreatedAt = DateTimeOffset.UtcNow
};
foreach (var item in request.Items)
{
order.Items.Add(new OrderItem
{
ProductId = item.ProductId,
Quantity = item.Quantity,
UnitPrice = item.UnitPrice
});
}
db.Orders.Add(order);
await db.SaveChangesAsync();
await transaction.CommitAsync();Do not extend that transaction by directly updating the Inventory database. Combining two databases in one atomic operation introduces distributed transaction, connection, timeout, and compensation concerns. More importantly, it couples Order and Inventory so tightly that they are no longer independently deployable services.
Later lessons will introduce more suitable flows: Order is created, an event is published, and Inventory consumes the event to create a reservation. If reservation fails, the Order state can become cancelled or pending. This eventual consistency model reflects the operating conditions of distributed systems more realistically.
Common mistakes
- Using one DbContext: Putting Order and Inventory entities in the same context blurs ownership boundaries.
- Sharing one connection string: If both services can access the same database, data ownership exists only on paper.
- Creating cross-service foreign keys: Database foreign keys should be limited to relationships inside one ownership boundary.
- Always reading the current product price from Catalog: Historical orders should not change when the catalog changes.
- Writing to two databases for every request: This creates high coupling and complex failure scenarios.
- Managing all migrations in one project: Each service should manage its own schema and migration history.
Short practice exercise
- Add the SQL Server EF Core provider packages to the Order and Inventory projects.
- Create the two
DbContextclasses shown above. - Add the
orderdbandinventorydbdatabase resources to the AppHost. - Create one migration in each service.
- Create a sample order through the Order API and a stock record through the Inventory API.
- Try adding code that queries an Inventory table directly from Order, then explain why that approach violates the service boundary.
Conclusion
In this lesson, we designed Order and Inventory as separate data ownership boundaries, not merely as separate projects. Each service now has its own entity model, DbContext, migration history, and database connection. The Aspire AppHost defines these resources in one application model and simplifies local orchestration and dependency management.
Independent data layers are one of the most important and frequently misunderstood microservice principles. Using contracts, APIs, and events instead of direct table sharing keeps transaction boundaries explicit, limits the impact of changes, and prepares the application for the resilience and messaging topics covered in the next lessons.
Sources
- https://learn.microsoft.com/en-us/azure/architecture/microservices/design/data-considerations
- https://learn.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/data-sovereignty-per-microservice
- https://learn.microsoft.com/en-us/dotnet/aspire/database/sql-server-integrations
- https://learn.microsoft.com/en-us/dotnet/aspire/database/ef-core-migrations
- https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations