Tutorials Entity Framework Core Tutorial
Complex Relationships in EF Core
Complex Relationships in EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 50 of 100
Complex Relationships in EF Core
Beginner ✓ → Intermediate ✓ → Advanced → Professional
Advanced · 3 — Production skills · ~6 min · Module 5: Relationships
What is this?
Complex relationships combine multiple patterns — optional FKs, many-to-many with payload, owned types, table splitting, and inheritance — in one bounded context.
Why should you care?
ShopNest orders link Customer, shipping address snapshot, payments, and items — real models rarely stop at simple one-to-many.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; } = null!;
public Address ShipTo { get; set; } = new(); // owned type
public ICollection<OrderItem> Items { get; set; } = new();
public ICollection<Payment> Payments { get; set; } = new();
}
modelBuilder.Entity<Order>().OwnsOne(o => o.ShipTo);
modelBuilder.Entity<OrderItem>()
.HasOne(i => i.Product).WithMany().HasForeignKey(i => i.ProductId);
What happened?
- OwnsOne embeds ShipTo columns on Orders table.
- Order links Customer (many-to-one), Items (one-to-many), Payments (one-to-many) simultaneously.
Practice next
- Draw ER diagram before Fluent API.
- Configure each relationship explicitly in complex areas.
- Split bounded contexts if graph becomes unwieldy.
- Add Payment many-to-one Order with optional partial payments.
- Map inheritance hierarchy for Product types — TPH vs TPT.
Remember
Real domains mix relationship types. Owned types embed value objects. Explicit Fluent config prevents convention surprises.
ShopNest checkout model
Order aggregates owned ShipTo address, line items, and payment attempts.
Outcome: Single SaveChanges persists coherent checkout graph matching business document.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!