The entity type 'X' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'

Problem

I got the following error when I ran the add-migration command for the following entity.

  public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }   
    }
The entity type 'Student' requires a primary key to be defined. If you intended to use a keyless entity type, 
call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types,
see https://go.microsoft.com/fwlink/?linkid=2141943.

Solutions

The error message is clear. The entity requires a primary key to be defined. If the entity is a keyless entity, we have to specify it explicitly in OnModelCreating method. Obviously, the first solution is defining a primary key for the entity. 

Solution 1

Define a primary key. The error will disappear when the entity class is modified as follows. Here, when you have an entity with a property named Id, EF Core accepts that property as the primary key by EF Core conventions.

 public class Student
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }   
    }

Solution 2

If you want a field with a custom name as the primary key, the following solution will work. Here, the key attribute is used to mention the primary key property name.

using System.ComponentModel.DataAnnotations;
public class Student
    {
        [Key]
        public int SID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }   
    }

Solution 3

If you don't want a primary key for the entity, add the following code inside OnModelCreating method of your DbContext class.

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>().HasNoKey();
        }

Solution 4

If you are using EF Core 5, you can use [Keyless] Data Annotation attribute to indicate that the entity doesn't need a primary key.

using Microsoft.EntityFrameworkCore;
[Keyless]
public class Student
    {        
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }  
    }

Search