Bartosz Sobczyński Bartosz Sobczyński - 3 months ago 34
C# Question

EntityType has no key defined, despite using [Key]

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?

Answer

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