# EF Core: The entity type 'X' requires a primary key to be defined

**Code:** `requires a primary key to be defined` · **Category:** .NET · **Seen on:** .NET

EF Core found an entity class without a key property it can recognise.

## 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

1. Add [Key] or modelBuilder.Entity<T>().HasKey(...)
2. Use HasNoKey() for views
3. Remove accidental DbSet/navigation

## Detailed fix by platform

### C#

1. 

```csharp
modelBuilder.Entity<OrderLine>().HasKey(l => new { l.OrderId, l.LineNo });
modelBuilder.Entity<SalesReport>().HasNoKey().ToView("vw_sales");
```


## How to diagnose

1. **Entity** — Named in the error
2. **Key** — Property naming

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/dotnet/entity-type-requires-primary-key)
