EF Core: The entity type 'X' requires a primary key to be defined
EF Core found an entity class without a key property it can recognise.
requires a primary key to be definedIf you intended to use a keyless entity type, call 'HasNoKey' Meaning
EF looks for Id or <TypeName>Id. Other names need [Key] or HasKey(); keyless query types need HasNoKey(). DTOs accidentally exposed as DbSet also trigger it.
Common causes
- Key property not named Id/<Type>Id
- Composite key not configured
- Class meant to be keyless (view/query)
- Non-entity class included as DbSet or navigation
⚡ Quick fix
- Add [Key] or modelBuilder.Entity<T>().HasKey(...)
- Use HasNoKey() for views
- Remove accidental DbSet/navigation
Detailed fix by platform
C#
- csharp
modelBuilder.Entity<OrderLine>().HasKey(l => new { l.OrderId, l.LineNo }); modelBuilder.Entity<SalesReport>().HasNoKey().ToView("vw_sales");
How to diagnose
- Entity — Named in the error
- Key — Property naming
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- A second operation was started on this context EF Core: A second operation was started on this context instance before a previous operation completed
- Cannot access a disposed context instance ObjectDisposedException: Cannot access a disposed context instance
- cannot be tracked because another instance with the same key The instance of entity type 'X' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked
Most viewed in .NET
- FileNotFoundException assembly Could not load file or assembly 'X, Version=…' or one of its dependencies
- Unable to cast object of type System.InvalidCastException: Unable to cast object of type 'X' to type 'Y'
- NullReferenceException System.NullReferenceException: Object reference not set to an instance of an object
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 13 Oct 2026