Volume 3 · Chapter 4 — Entity Framework Core and Data Access Engineering

Relationships and Modeling

Goutham Mayaluri 8 min read .NETC#

4.1 Introduction

How you model entities and their relationships shapes the whole data layer - poor modeling creates slow queries, complex code, and tight coupling. EF Core supports one-to-one, one-to-many, and many-to-many relationships, configured with conventions, data annotations, or the Fluent API. The deeper lesson is that yourdomainmodel should be driven by business behavior and consistency boundaries, not by a naive copy of database tables.

4.2 Relationship Types

Relationships are expressed with navigation properties and foreign keys. One-to-many (a customer has many orders) is the most common; many-to-many (students and courses) is handled by EF Core directly without a manual join entity in simple cases; one-to-one (a customer and its profile) associates exactly one of each.

flowchart TB
  C["Customer"] -- "1 : N" --> O["Order"]
  O -- "1 : N" --> I["OrderItem"]
  C -- "1 : 1" --> P["CustomerProfile"]
  S["Student"] -- "N : N" --> Cr["Course"]

public sealed class Customer
{
    public Guid Id { get; set; }
    public string Name { get; set; } = "";
    public ICollection<Order> Orders { get; set; } = new List<Order>();  // navigation
}

public sealed class Order
{
    public Guid Id { get; set; }
    public Guid CustomerId { get; set; }        // foreign key
    public Customer Customer { get; set; } = null!;
}

4.3 Fluent API vs Data Annotations

Data annotations ([Key],[Required]) configure simple cases inline on the entity. The Fluent API (inOnModelCreating) gives full control over relationships, keys, constraints, indexes, and mappings, and keeps configuration out of the domain classes - preferred for anything beyond the basics.


protected override void OnModelCreating(ModelBuilder b)
{
    b.Entity<Order>()
        .HasOne(o => o.Customer)
        .WithMany(c => c.Orders)
        .HasForeignKey(o => o.CustomerId)
        .OnDelete(DeleteBehavior.Restrict);

    b.Entity<Customer>().OwnsOne(c => c.Address);   // owned value object
}

4.4 Owned Entities and Value Objects

An owned entity has no independent identity and belongs entirely to its owner - the natural way to map value objects likeAddressorMoney, which are defined by their values, not an id. Modeling money as aMoneyvalue object rather than a rawdecimaleliminates a class of currency and rounding bugs.

4.5 Aggregates: Domain Model vs Database Model

In domain-driven design, entities are grouped into aggregates with a consistency boundary and a root that is the only entry point for changes (an Order aggregate containing its OrderItems). The key architectural point is that the domain model expresses business behavior and invariants, while the database model optimizes storage and retrieval - they overlap but are not the same, and forcing the domain to mirror tables leads to an anemic, coupled design.

Senior Interview Question

How do you decide entity and aggregate boundaries?

I draw boundaries from the business - its concepts, ownership rules, and consistency requirements - rather than from the database tables. An aggregate is a cluster of entities and value objects that must be kept consistent together and is treated as a single unit, with one entity as the aggregate root that is the only way external code changes the cluster, so all the invariants inside can be enforced atomically. To decide the boundary I ask: which pieces of data must always be consistent with each other in a single transaction (those belong in the same aggregate), and which can be eventually consistent (those belong in separate aggregates, referenced by id). For example, an Order and its OrderItems form one aggregate because the order total and the “no changes after submission” rule must hold across them atomically, with Order as the root; the Customer, however, is a separate aggregate referenced by id, because a customer’s data doesn’t need to be transactionally consistent with every order. I keep aggregates as small as possible - large aggregates cause lock contention and load huge object graphs - preferring to reference other aggregates by id rather than by object navigation, and to modify one aggregate per transaction, coordinating across aggregates with domain events and eventual consistency. I also let ownership guide it: data that has no independent life and belongs entirely to one entity (an address, a line item) lives inside that aggregate, often as an owned value object. The anti-pattern I avoid is deriving entities and boundaries by mirroring database tables, which produces boundaries based on storage structure rather than business consistency and behavior. So the decision is driven by consistency requirements (what must be atomic), ownership, and the business’s own concepts and language - which yields aggregates that protect real invariants and scale well, rather than a model that just reflects the schema.

Senior Interview Question

What are owned entities / value objects, and when do you use them?

An owned entity in EF Core is a type that has no identity of its own and belongs completely to another entity - it’s stored as part of the owner (typically in the same table’s columns, or a related table) and has no independentDbSetor lifecycle; it exists only as a component of its owner. Owned entities are how EF Core mapsvalue objects- domain concepts defined entirely by their attribute values rather than by an identity, such as anAddress(street, city, postcode), aMoney(amount, currency), a date range, or contact information. I use them when a concept is a value, not a thing with a lifecycle: you don’t reference an address by an id or track it independently, you just have the customer’s address as part of the customer. The benefits are both modeling and correctness: value objects are immutable and compared by value, which eliminates a whole class of bugs from shared mutable state and from primitive obsession - for instance, modeling money as aMoneyvalue object with amount and currency, rather than a baredecimal, prevents currency-mismatch and rounding errors and lets you attach behavior (formatting, addition with currency checks) to the concept. They also keep the owner’s aggregate cohesive, since the value object lives inside it. In EF Core you configure them withOwnsOne/OwnsManyin the Fluent API, and EF handles persisting them as part of the owner. So I reach for owned entities / value objects whenever a piece of data is a value that belongs wholly to another entity and has no independent identity - addresses, money, measures, ranges - which produces a richer, safer domain model than scattering primitive fields, and is a core DDD tactical pattern that EF Core supports directly.

Principal Engineer Question

Should the domain model always match the database schema? Why or why not?

No - the domain model and the database schema serve different purposes and should be allowed to differ, though they’ll overlap. The domain model exists to express business behavior, rules, and invariants in the language of the business: it’s organized around aggregates and consistency boundaries, encapsulates behavior in entities and value objects, and is shaped by how the business thinks and what must stay consistent. The database schema exists to store and retrieve data efficiently: it’s organized around normalization (or denormalization for performance), indexing, storage cost, and query patterns. Forcing the domain to mirror the tables one-to-one produces the classic anti-patterns - an anemic domain model that’s just data bags matching rows with logic scattered elsewhere, boundaries dictated by table structure rather than business consistency, and tight coupling of the business logic to persistence details so the schema can’t evolve without churning the domain and vice versa. Conversely, forcing the schema to mirror a rich object model can produce inefficient storage and queries. So I let each be optimized for its job and use EF Core’s mapping capabilities to bridge them: owned entities and value objects map rich domain concepts onto columns/tables, the Fluent API configures how aggregates and relationships persist, shadow properties and backing fields let the domain hide persistence concerns, and I can map a domain aggregate across tables or combine tables into one entity as appropriate. Clean Architecture reinforces this - the domain defines what it needs through abstractions and the infrastructure/EF layer implements the persistence, so the business logic doesn’t depend on the schema. That said, pragmatism matters: for simple CRUD with little business logic, a model that closely follows the tables is fine and simpler, and over-abstracting there is wasteful; the divergence between domain and schema is worth it precisely where there’s meaningful business complexity to protect. So the principled answer is that domain and database models are related but distinct concerns - one optimized for business behavior and consistency, the other for storage and retrieval - and they should be allowed to differ, mapped by the ORM, rather than assumed to be the same, because conflating them couples business logic to storage and undermines both a clean domain and an efficient schema.

4.6 Production Scenario

A banking application initially models customers, accounts, transactions, and payments by directly mirroring database tables, producing tightly coupled entities, sprawling navigation properties, and slow queries. The team redesigns around business aggregates with clear consistency boundaries (an Account aggregate, a Payment aggregate), models Money and Address as owned value objects, references other aggregates by id, and tunes loading strategies - decoupling the domain from the schema and speeding up queries.

Chapter Revision Notes

  • Model relationships with navigation properties and foreign keys; prefer the Fluent API for non-trivial config.
  • Owned entities map value objects (Address, Money) with no independent identity.
  • Aggregates define consistency boundaries with a single root - keep them small, reference others by id.
  • The domain model expresses business behavior; the database model optimizes storage - they need not match.
  • Draw boundaries from business consistency and ownership, not from table structure.