Tutorials Entity Framework Core Tutorial
Composite Keys in EF Core
Composite Keys 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 19 of 100
Composite Keys in EF Core
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Foundations · ~6 min · Module 2: Code First Approach
What is this?
A composite key uses two or more properties together as the primary key. Configure it with [PrimaryKey] attribute or Fluent HasKey when a single Id column is not enough.
Why should you care?
ShopNest warehouse bin locations may be unique by WarehouseId + Aisle + Bin — composite keys model natural identifiers without surrogate Id.
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 WarehouseBin
{
public int WarehouseId { get; set; }
public string Aisle { get; set; } = "";
public string BinCode { get; set; } = "";
public int ProductId { get; set; }
}
// Fluent API:
modelBuilder.Entity<WarehouseBin>()
.HasKey(b => new { b.WarehouseId, b.Aisle, b.BinCode });
What happened?
- HasKey with anonymous type defines composite PK.
- EF creates clustered index on all three columns.
- FindAsync requires all key parts.
Practice next
- Identify a natural composite key in ShopNest inventory (e.g., wishlist UserId + ProductId).
- Configure HasKey and add migration.
- Try FindAsync with all key values vs missing one.
- Model OrderItem with composite key OrderId + LineNumber instead of Id.
- Query by key: _context.WarehouseBins.Find(1, "A", "B12").
Remember
Composite keys combine multiple columns as PK. Configure via Fluent HasKey or [PrimaryKey]. Surrogate keys are often simpler for ORM apps.
ShopNest stock location key
Inventory service uses WarehouseId+Aisle+BinCode composite key to prevent duplicate bin assignments.
Outcome: Natural key matches warehouse labels on physical shelves.
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!