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

本文关键字:key 定义 EntityType | 更新日期: 2023-09-27 18:05:20

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

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. 

My Book类是这样的:

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]注释。什么好主意吗?

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

当使用反射来检测PropertyInfo实例时,必须给EntityFramework所有的东西,只使用那些公共的。你只需要将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; }
}