EntityType 'SelectListItem' has no defined key. Define the key for this entity type

advertisements

i Have a Model Class

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public ICollection<SelectListItem> CourseList { get; set; }
}

and the

public class StudentContext : DbContext
{
    public DbSet<Student> Students { get; set; }
}

and i try ti use it as

List<Student> sList =  db.Students.ToList();

and i am getting following error

\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'SelectListItem' has no key defined. Define     the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'SelectListItems' is based on type   'SelectListItem' that has no keys defined.

Please suggest where i am doing wrong.


You should not be attempting to store SelectListItem in the database, as this is MVC specific concept. Instead create a custom entity class and use it instead;

public class Course
{
    public int CourseId { get; set; }
    public string CourseTitle  { get; set; }
}

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public ICollection<Course> CourseList { get; set; }
}

public class StudentContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }
}