Entity Framework Core Interview Question #8

How does EF Core determine the primary key of an entity?

EF Core Fundamentals & DbContext Junior Beginner

Quick Interview Answer

By convention, EF Core recognizes a property named Id or <EntityName>Id as the primary key for many common entity types.

Detailed Explanation

By convention, EF Core recognizes a property named Id or <EntityName>Id as the primary key for many common entity types.

A key can also be configured explicitly using data annotations or the Fluent API. Explicit configuration is useful for non-conventional names, composite keys, or advanced mapping requirements.

Primary keys uniquely identify tracked entity instances and are fundamental to relationships and updates.

Code Example

public class Product
{
    public int ProductId { get; set; }
}

// Fluent configuration:
modelBuilder.Entity<Product>()
    .HasKey(p => p.ProductId);