1

I am configuring context in my application. These are throwing expection:

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

It looks like this:

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 class looks like this:

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

As you see, there's [Key] annotation. Any ideas?

ekad
  • 14,436
  • 26
  • 44
  • 46

1 Answers1

1

Everything must be given to EntityFramework when use reflection to detect PropertyInfo instances, only use those that are public.You just need to set BookId property as 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; }
}
Jose Rodriguez
  • 9,753
  • 13
  • 36
  • 52