Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityType has no key defined error

The Model class should be changed to :

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Models
{
    [Table("studentdetails")]
    public class student
    {
        [Key]
        public int RollNo { get; set; }

        public string Name { get; set; }

        public string Stream { get; set; }

        public string Div { get; set; }
    }
}

  1. Make sure public members of student class are defined as properties w/ {get; set;} (yours are public variables - a common mistake).

  2. Place a [Key] annotation on top of your chosen property.


There are several reasons this can happen. Some of these I found here, others I discovered on my own.

  • If the property is named something other than Id, you need to add the [Key] attribute to it.
  • The key needs to be a property, not a field.
  • The key needs to be public
  • The key needs to be a CLS-compliant type, meaning unsigned types like uint, ulong etc. are not allowed.
  • This error can also be caused by configuration mistakes.

i know that this post is late but this solution helped me:

    [Key]
    [Column(Order = 0)]
    public int RoleId { get; set; }

added [Column(Order = 0)] after [Key] can be added by increment by 1:

    [Key]
    [Column(Order = 1)]
    public int RoleIdName { get; set; }

etc...


In my case, I was getting the error when creating an "MVC 5 Controller with view, using Entity Framework".

I just needed to Build the project after creating the Model class and didn't need to use the [Key] annotation.


Using the [key] didn't work for me but using an id property does it. I just add this property in my class.

public int id {get; set;}