EntityType 没有定义键,尽管使用 [Key]

EntityType has no key defined, despite using [Key]

我正在我的应用程序中配置上下文。这些是抛出期望:

public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<Book> Books { get; set; }

看起来像这样:

BookList.Models.Book: : EntityType 'Book' has no key defined. Define the key      for this EntityType.
Books: EntityType: EntitySet 'Books' is based on type 'Book' that has no keys defined. 

我的书 class 看起来像这样:

public class Book
{
    [Display(Name = "Id:")]
    [Key]
    private int BookId { get; set; }

    [Display(Name = "Title:")]
    [MaxLength(35)]
    [Required]
    private string Title { get; set; }

    [Display(Name = "Description:")]
    [MaxLength(300)]
    private string Description { get; set; }
}

如您所见,有 [Key] 注释。有什么想法吗?

使用反射检测 PropertyInfo 实例时,必须将所有内容都提供给 EntityFramework,仅使用那些 public.You 只需要将 BookId 属性 设置为 public:

public class Book
{
    [Display(Name = "Id:")]
    [Key]
    public int BookId { get; set; }

    [Display(Name = "Title:")]
    [MaxLength(35)]
    [Required]
    private string Title { get; set; }

    [Display(Name = "Description:")]
    [MaxLength(300)]
    private string Description { get; set; }
}