Tutorials Entity Framework Core Tutorial
One-to-Many Relationships in EF Core
One-to-Many 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 42 of 100
One-to-Many Relationships in EF Core
Beginner ✓ → Intermediate ✓ → Advanced → Professional
Advanced · 3 — Production skills · ~6 min · Module 5: Relationships
What is this?
One-to-many links one parent to many children — Category has many Products, Customer has many Orders. FK lives on the many side.
Why should you care?
ShopNest categories organize thousands of products — one-to-many is the backbone of catalog navigation.
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 Category
{
public int Id { get; set; }
public string Name { get; set; } = "";
public ICollection<Product> Products { get; set; } = new List<Product>();
}
// Fluent:
modelBuilder.Entity<Product>()
.HasOne(p => p.Category)
.WithMany(c => c.Products)
.HasForeignKey(p => p.CategoryId);
What happened?
- CategoryId on Product is FK.
- WithMany on Category completes bidirectional mapping.
- EF creates index on CategoryId automatically.
Practice next
- Ensure FK property type matches parent PK type.
- Configure delete behavior — Restrict vs Cascade for categories.
- Query products by CategoryId with index support.
- Add required Category on Product — migrate NOT NULL CategoryId.
- Filter products: _context.Products.Where(p => p.Category!.Name == "Electronics").
Remember
FK on many side points to one parent. ICollection on parent lists children. Configure OnDelete explicitly.
ShopNest category browse
Browse Electronics loads Products where CategoryId matches via indexed FK.
Outcome: Flipkart-style aisle navigation backed by simple one-to-many schema.
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!