Tutorials Entity Framework Core Tutorial
Relationships in Code First EF Core
Relationships in Code First 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 18 of 100
Relationships in Code First EF Core
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Foundations · ~6 min · Module 2: Code First Approach
What is this?
Relationships connect entities through foreign key properties and navigation properties — Customer has many Orders, Order has many OrderItems, Product belongs to Category.
Why should you care?
ShopNest checkout loads related data; relationships generate FK constraints and enable Include without manual join SQL.
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 OrderItem
{
public int Id { get; set; }
public int OrderId { get; set; }
public Order Order { get; set; } = null!;
public int ProductId { get; set; }
public Product Product { get; set; } = null!;
public int Quantity { get; set; }
}
What happened?
- OrderId and ProductId are FK columns.
- Order and Product navigations let EF traverse graphs and configure cascades in Fluent API.
Practice next
- Wire Order ↔ Customer and OrderItem ↔ Product navigations both ways.
- Configure delete behavior in Fluent API for Order–OrderItem.
- Add migration and verify FK constraints in SSMS.
- Make OrderItem–Product relationship optional with nullable ProductId (if business allows).
- Add shadow property FK via Fluent API without C# property.
Remember
FK property + navigation defines a relationship. Configure delete behavior explicitly for production. Bidirectional navigations clarify the model.
ShopNest order graph
OrderItem rows tie each purchased Product to an Order with enforced FK integrity.
Outcome: Orphan line items cannot exist — refunds always trace to a product.
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!