LESSON 7 OF 18

7. Related Resources and Business Rules

Configure Category-Product and Customer-Order relationships with EF Core, design related-resource endpoints, and enforce stock, pricing, and availability rules during order creation.

45 dk 80

Introduction

A professional REST API does not manage resources in isolation. In a real e-commerce system, products belong to categories, orders belong to customers, and order lines refer to products. If these relationships are modeled poorly, endpoints become difficult to understand, unnecessary data is returned to clients, and critical business rules become scattered across controllers.

In this lesson, we will work with two core relationships: Category-Product and Customer-Order. We will also enforce rules during order creation, including product existence, product availability, stock sufficiency, and preservation of the current product price. The objective is not merely to insert a row into the database, but to create an API that is consistent, reliable, and predictable for client applications.

We will assume that centralized exception handling and ProblemDetails were implemented in the previous lesson. Domain-level failures in this lesson will use that mechanism and will be mapped to appropriate HTTP status codes.

1. Expressing relationships in the domain model

A category can contain many products, while each product belongs to one category. This is a typical one-to-many relationship. Similarly, a customer can have many orders, while each order belongs to one customer.

public sealed class Category {    public int Id { get; set; }    public required string Name { get; set; }    public bool IsActive { get; set; } = true;    public ICollection<Product> Products { get; set; } = []; } public sealed class Product {    public int Id { get; set; }    public required string Name { get; set; }    public decimal Price { get; set; }    public int StockQuantity { get; set; }    public bool IsActive { get; set; } = true;    public int CategoryId { get; set; }    public Category Category { get; set; } = null!; } public sealed class Customer {    public int Id { get; set; }    public required string Email { get; set; }    public required string FullName { get; set; }    public ICollection<Order> Orders { get; set; } = []; } public sealed class Order {    public int Id { get; set; }    public DateTime CreatedAtUtc { get; set; }    public string Status { get; set; } = "Pending";    public int CustomerId { get; set; }    public Customer Customer { get; set; } = null!;    public ICollection<OrderLine> Lines { get; set; } = []; }

Product contains both a CategoryId foreign key and a Category navigation property. The foreign key explicitly represents the relationship in the relational database. The navigation property provides convenient access to the related object in C#.

An order also needs an OrderLine model. The total of a historical order must not change when the product price changes later. For that reason, the line stores the product price at the time the order was created.

public sealed class OrderLine {    public int Id { get; set; }    public int Quantity { get; set; }    public decimal UnitPrice { get; set; }    public int OrderId { get; set; }    public Order Order { get; set; } = null!;    public int ProductId { get; set; }    public Product Product { get; set; } = null!; }

2. Configuring EF Core relationships

Conventions can discover many relationships automatically. However, in a critical application, explicitly defining model behavior makes the design safer and easier to review. The following configuration specifies foreign keys, delete behavior, and decimal precision.

protected override void OnModelCreating(ModelBuilder modelBuilder) {    modelBuilder.Entity<Category>()        .HasMany(category => category.Products)        .WithOne(product => product.Category)        .HasForeignKey(product => product.CategoryId)        .OnDelete(DeleteBehavior.Restrict);    modelBuilder.Entity<Customer>()        .HasMany(customer => customer.Orders)        .WithOne(order => order.Customer)        .HasForeignKey(order => order.CustomerId)        .OnDelete(DeleteBehavior.Restrict);    modelBuilder.Entity<OrderLine>()        .HasOne(line => line.Product)        .WithMany()        .HasForeignKey(line => line.ProductId)        .OnDelete(DeleteBehavior.Restrict);    modelBuilder.Entity<Product>()        .Property(product => product.Price)        .HasPrecision(18, 2);    modelBuilder.Entity<OrderLine>()        .Property(line => line.UnitPrice)        .HasPrecision(18, 2); }

We use DeleteBehavior.Restrict to prevent deleting a category or customer from automatically deleting products or historical orders. In production systems, deactivation through a property such as IsActive is often safer than physical deletion.

3. Designing endpoints for related resources

There are two common endpoint styles for related data. The first exposes the related collection as a sub-resource:

  • GET /api/categories/{categoryId}/products
  • GET /api/customers/{customerId}/orders

The second queries the main collection using a filter:

  • GET /api/products?categoryId=3
  • GET /api/orders?customerId=12

A sub-resource endpoint communicates the relationship clearly and is readable when the client already has the parent context. However, avoid deeply nested URL chains. Instead of /customers/12/orders/45/lines/3/product, expose related resources through focused endpoints.

Collection endpoints should return DTOs rather than entities. DTOs prevent navigation properties from creating cycles and avoid exposing fields that clients do not need.

public sealed record ProductSummaryDto(    int Id,    string Name,    decimal Price,    int StockQuantity,    int CategoryId); [HttpGet("{categoryId:int}/products")] public async Task<ActionResult<IReadOnlyList<ProductSummaryDto>>> GetProducts(    int categoryId,    CancellationToken cancellationToken) {    var categoryExists = await db.Categories        .AnyAsync(category => category.Id == categoryId && category.IsActive,            cancellationToken);    if (!categoryExists)        return NotFound();    var products = await db.Products        .AsNoTracking()        .Where(product => product.CategoryId == categoryId && product.IsActive)        .OrderBy(product => product.Name)        .Select(product => new ProductSummaryDto(            product.Id,            product.Name,            product.Price,            product.StockQuantity,            product.CategoryId))        .ToListAsync(cancellationToken);    return Ok(products); }

A missing category and an existing category with no products are different situations. If the category exists but contains no products, the usual response is 200 OK with []. If the category does not exist, 404 Not Found is appropriate.

4. Order DTOs and the business workflow

An order creation request should contain only the information the client is allowed to provide. Do not allow the client to submit the product name, price, or total amount. The server must calculate these values.

public sealed record CreateOrderRequest(    int CustomerId,    IReadOnlyList<CreateOrderLineRequest> Lines); public sealed record CreateOrderLineRequest(    int ProductId,    int Quantity); public sealed record OrderCreatedDto(    int Id,    int CustomerId,    decimal Total,    string Status);

A practical application service can follow this sequence:

  1. Check that the request contains lines and that every quantity is positive.
  2. Verify that the customer exists and is active when that rule applies.
  3. Load all requested products in one database query.
  4. Check that every requested product exists.
  5. Reject inactive products.
  6. Check whether available stock covers the requested quantity.
  7. Create order lines using the current server-side product prices.
  8. Decrease stock and save the order within the same transaction.

The client must not provide the price or total. A client could submit an old or manipulated price. The UnitPrice field on the order line is an immutable snapshot of the price at order time.

5. Creating an order

[HttpPost] public async Task<ActionResult<OrderCreatedDto>> Create(    CreateOrderRequest request,    CancellationToken cancellationToken) {    if (request.Lines.Count == 0)        throw new DomainRuleException(            "Order must contain at least one line.",            "order.lines.empty");    if (request.Lines.Any(line => line.Quantity <= 0))        throw new DomainRuleException(            "Quantity must be greater than zero.",            "order.quantity.invalid");    var customerExists = await db.Customers        .AnyAsync(customer => customer.Id == request.CustomerId,            cancellationToken);    if (!customerExists)        throw new ResourceNotFoundException(            "Customer was not found.",            "customer.not_found");    var requestedQuantities = request.Lines        .GroupBy(line => line.ProductId)        .ToDictionary(group => group.Key,            group => group.Sum(line => line.Quantity));    var productIds = requestedQuantities.Keys.ToArray();    var products = await db.Products        .Where(product => productIds.Contains(product.Id))        .ToDictionaryAsync(product => product.Id, cancellationToken);    foreach (var item in requestedQuantities)    {        if (!products.TryGetValue(item.Key, out var product))            throw new ResourceNotFoundException(                $"Product {item.Key} was not found.",                "product.not_found");        if (!product.IsActive)            throw new DomainRuleException(                $"Product {product.Id} is not available.",                "product.unavailable");        if (product.StockQuantity < item.Value)            throw new DomainRuleException(                $"Insufficient stock for product {product.Id}.",                "product.insufficient_stock");    }    await using var transaction = await db.Database        .BeginTransactionAsync(cancellationToken);    var order = new Order    {        CustomerId = request.CustomerId,        CreatedAtUtc = DateTime.UtcNow,        Status = "Pending"    };    foreach (var item in requestedQuantities)    {        var product = products[item.Key];        product.StockQuantity -= item.Value;        order.Lines.Add(new OrderLine        {            ProductId = product.Id,            Quantity = item.Value,            UnitPrice = product.Price        });    }    db.Orders.Add(order);    await db.SaveChangesAsync(cancellationToken);    await transaction.CommitAsync(cancellationToken);    var total = order.Lines.Sum(line => line.Quantity * line.UnitPrice);    var response = new OrderCreatedDto(        order.Id,        order.CustomerId,        total,        order.Status);    return CreatedAtAction(nameof(GetById),        new { id = order.Id }, response); }

If the same product appears in multiple request lines, combining quantities with GroupBy and Sum is important. Otherwise, a stock check performed separately for each line might allow the total requested quantity to exceed available stock.

6. Returning domain failures with ProblemDetails

These failures are not necessarily syntax or model-validation failures. For example, insufficient stock is a business conflict even though the JSON request is structurally valid. Returning such a condition as 500 Internal Server Error would be misleading for clients.

Example domain exception types:

public sealed class DomainRuleException : Exception {    public string Code { get; }    public DomainRuleException(string detail, string code)        : base(detail) => Code = code; } public sealed class ResourceNotFoundException : Exception {    public string Code { get; }    public ResourceNotFoundException(string detail, string code)        : base(detail) => Code = code; }

The centralized exception handler can map these exceptions as follows:

SituationExample codeHTTP result
Resource does not existcustomer.not_found404 Not Found
Product is unavailableproduct.unavailable409 Conflict
Insufficient stockproduct.insufficient_stock409 Conflict
Invalid domain requestorder.lines.empty422 Unprocessable Entity

409 Conflict is useful when the request conflicts with the current state of a resource. Insufficient stock or a product being removed from sale can fit this category. 422 Unprocessable Entity can represent a syntactically valid JSON document that cannot be processed according to domain rules. The important point is to choose a consistent policy and document it as part of the API contract.

Allow clients to rely on a machine-readable code field in ProblemDetails, not only on the HTTP status. Human-readable detail messages should not be treated as stable UI contracts.

7. Common mistakes

  • Returning entities directly: Navigation properties can create cycles, expose too much data, or leak sensitive fields.
  • Accepting the price from the client: The client can manipulate it. Always read the current price from the server-side product record.
  • Skipping a transaction: If the order is saved but stock reduction fails, the system becomes inconsistent.
  • Querying products one by one: One query per line can create an N+1 problem. Load products in a single query.
  • Only hiding inactive products from search results: Critical workflows such as order creation must validate IsActive independently.
  • Returning 404 for an empty collection: If the category exists but has no products, a collection endpoint should usually return 200 OK with an empty list.
  • Exposing exception messages directly: Internal implementation details and SQL information must not leak to clients.

8. Short practice exercise

Complete the following tasks:

  1. Implement GET /api/customers/{customerId}/orders.
  2. Return the order ID, creation date, status, and total through a DTO.
  3. Return 404 when the customer does not exist, and 200 with an empty list when the customer exists but has no orders.
  4. Add tests for inactive products, insufficient stock, and a missing customer.
  5. Verify that when the same product appears in two request lines, stock validation uses the combined quantity.

Conclusion

Related resources allow a REST API to expose the actual domain structure in a clear way. Explicit EF Core relationship configuration, carefully designed sub-resource endpoints, and DTO boundaries are essential for maintainability. In critical workflows such as order creation, stock, price, and availability rules should be enforced centrally in the application or domain layer.

In the next lesson, we will improve these endpoints with pagination, filtering, and sorting. This will make related-resource queries not only correct, but also efficient when working with large data sets.

Sources