实体类型需主键错误排查:Consoles等表已设主键仍报错
解决EF Core中“entity type requires primary key”错误
你遇到的问题是EF Core的主键约定识别失败导致的。EF Core默认会识别名为Id或者[实体类名]Id的属性作为主键,但你的三个实体类的主键命名不符合这个约定:
Headphone类的主键是HeadphonesId(带复数后缀),和类名Headphone不匹配KeyboardAndMouse类的主键是KmId,完全不符合约定格式Consoles类的主键是ConsoleId(单数形式),和类名Consoles(复数形式)不匹配
下面是两种可行的解决方法:
方法一:修改主键名称匹配EF Core约定
直接调整主键属性名,让它符合EF的默认识别规则:
public class Headphone:IEntity { // 改为和类名一致的单数形式 public int HeadphoneId { 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 { // 改为和类名一致的名称,或直接使用Id public int KeyboardAndMouseId { get; set; } public int ProductId { get; set; } public string Color { get; set; } } public class Consoles:IEntity { // 改为和类名一致的复数形式 public int ConsolesId { get; set; } public int ProductId { get; set; } public string Color { get; set; } public int GamepadNumber { get; set; } public int Capacity { get; set; } }
方法二:用[Key]特性显式标记主键
如果不想修改属性名,可以通过数据注解[Key]直接告诉EF Core哪个是主键,需要先引入using System.ComponentModel.DataAnnotations;命名空间:
using System.ComponentModel.DataAnnotations; public class Headphone:IEntity { [Key] 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 { [Key] public int KmId { get; set; } public int ProductId { get; set; } public string Color { get; set; } } public class Consoles:IEntity { [Key] 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; } }
内容的提问来源于stack exchange,提问作者HuseyinKan
相关产品推荐
相关产品推荐

