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

时间:2015-07-29 19:44:34

标签: c# entity-framework dbset

我正在我的应用程序中配置上下文。这些都是投掷:

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]注释。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

当使用反射来检测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; }
}