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

ぃ、小莉子 提交于 2019-12-23 01:45:28

问题


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.


回答1:


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



回答2:


Add [NotMapped] annotation to the LIST class

[NotMapped]
public List<SelectListItem> ListItems { get; set; }

NotMapped Code first convention dictates that every property that is of a supported data type is represented in the database. But this isn’t always the case in your applications. For example you might have a property in the Blog class that creates a code based on the Title and BloggerName fields. That property can be created dynamically and does not need to be stored. You can mark any properties that do not map to the database with the NotMapped annotation such as this BlogCode property.

[NotMapped] 
public string BlogCode 
{ 
    get 
    { 
        return Title.Substring(0, 1) + ":" + BloggerName.Substring(0, 1); 
    } 
}

You can refer to the link here on EF code first Data Annotations



来源:https://stackoverflow.com/questions/27091117/entitytype-selectlistitem-has-no-key-defined-define-the-key-for-this-entityty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!