Home > Software engineering >  I got a the entity type requires primary key error
I got a the entity type requires primary key error

Time:11-30

When i try to connect with my database and my class i got this error enter image description here But this error appear just for my Consoles,KeyboardMouse and Headphones tables. But they have already primary keys. enter image description here

and here is my context class

public class EcommContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=.;Database=eCommerce;Trusted_Connection=true");

    }
    public DbSet<Product> Products { get; set; }
    public DbSet<Card> Cards { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Consoles> Consoles { get; set; }
    public DbSet<Headphone> Headphones { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderDetail> OrderDetails { get; set; }
    public DbSet<Mouse> Mouses { get; set; }
    public DbSet<MousePad> MousePads { get; set; }
    public DbSet<Keyboard> Keyboards { get; set; }
    public DbSet<KeyboardAndMouse> KeyboardMouse { get; set; }
    public DbSet<Gamepad> Gamepads { get; set; }
    public DbSet<Computer> Computers { get; set; }
}

And my entity classes

public class Headphone:IEntity
{
    public int HeadphonesId { get; set; }
    public int ProductId { get; set; }
    public bool IsWireless { get; set; }
    public string Type { get; set; }
    public string Color { get; set; }
    public bool IsGaming { get; set; }
}

public class KeyboardAndMouse:IEntity
{
    public int KmId { get; set; }
    public int ProductId { get; set; }
    public string Color { get; set; }
}

public class Consoles:IEntity
{
    public int ConsoleId { get; set; }
    public int ProductId { get; set; }
    public string Color { get; set; }
    public int GamepadNumber { get; set; }
    public int Capacity { get; set; }
}

How can I solve that. Does anyone help me ?

CodePudding user response:

In your entity class you need to use [Key] annotation for primary key field. Try like below.

public class Headphone:IEntity
{
    [Key]
    public int HeadphonesId { get; set; }
}

public class KeyboardAndMouse:IEntity
{
    [Key]
    public int KmId { get; set; }
}

public class Consoles:IEntity
{
    [Key]
    public int ConsoleId { get; set; }
}

Please check this out for more information : https://learn.microsoft.com/en-us/ef/core/modeling/keys?tabs=data-annotations#configuring-a-primary-key

FYI - By convention, a property named Id or <type name>Id will be configured as the primary key of an entity.

So if you had HeadphoneId field in Headphone class then it will select that column as primary key by convention and no need to use [Key] annotation or Fluent API to define Primary key field.

  • Related