EntityType'SelectListItem'没有定义键.定义此EntityType的键

Kmr*_*Raz 1 model-view-controller asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我有一个模型类

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public ICollection<SelectListItem> CourseList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

public class StudentContext : DbContext
{
    public DbSet<Student> Students { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我试着用它作为

List<Student> sList =  db.Students.ToList();
Run Code Online (Sandbox Code Playgroud)

我得到了以下错误

\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.
Run Code Online (Sandbox Code Playgroud)

请告诉我在哪里做错了.

小智 9

[NotMapped]注释添加到LIST类

[NotMapped]
public List<SelectListItem> ListItems { get; set; }
Run Code Online (Sandbox Code Playgroud)

NotMapped代码优先约定规定,支持数据类型的每个属性都在数据库中表示.但在您的应用程序中并非总是如此.例如,您可能在Blog类中有一个属性,该属性根据Title和BloggerName字段创建代码.该属性可以动态创建,不需要存储.您可以使用NotMapped注释(例如此BlogCode属性)标记未映射到数据库的任何属性.

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

您可以在EF代码的第一个数据注释中参考此处的链接