EntityType 'SelectListItem' has no key def

2019-06-02 08:55发布

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.

2条回答
该账号已被封号
2楼-- · 2019-06-02 09:40

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

查看更多
beautiful°
3楼-- · 2019-06-02 09:46

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; }
}
查看更多
登录 后发表回答