【问题标题】:I got a the entity type requires primary key error我得到一个实体类型需要主键错误
【发布时间】:2022-11-30 17:07:23
【问题描述】:

当我尝试连接我的数据库和我的班级时,我收到了这个错误 但是这个错误只出现在我的控制台、键盘鼠标和耳机表上。但是他们已经有了主键。

这是我的上下文类 `

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; }
    }

`

我该如何解决。有人帮我吗?

【问题讨论】:

    标签: c#


    【解决方案1】:

    在您的实体类中,您需要对主键字段使用 [Key] 注释。像下面这样尝试。

    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; }
    }
    

    请查看此以获取更多信息:https://learn.microsoft.com/en-us/ef/core/modeling/keys?tabs=data-annotations#configuring-a-primary-key

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      相关资源
      最近更新 更多