【问题标题】:EntityType 'SelectListItem' has no key defined. Define the key for this EntityTypeEntityType 'SelectListItem' 没有定义键。定义此 EntityType 的键
【发布时间】:2014-11-23 16:14:09
【问题描述】:

我有一个模型类

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

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

我尝试将它用作

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

我收到以下错误

\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.

请提出我做错的地方。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 model-view-controller


    【解决方案1】:

    在 LIST 类中添加[NotMapped] 注解

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

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

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

    您可以参考这里的链接EF code first Data Annotations

    【讨论】:

      【解决方案2】:

      您不应该尝试将SelectListItem 存储在数据库中,因为这是 MVC 特定的概念。而是创建一个自定义实体类并改为使用它;

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

      【讨论】:

      • 我使用了selectitemlist,因为当我编辑学生时,我需要一个包含所有课程的列表框,我必须预先选择学生已经选择的课程!我只是想从现在开始通过 EF 进行检索,您能否让我知道您提到的上述代码的表结构,因为我很困惑如何在 Student 中映射 CourseList。 @dotnetom
      • @KmrRaz 为了显示数据库中的数据,您应该创建一个特定对象StudentViewModel。这是一个仅用于显示目的的特定对象。在此具有 SelectListItems 的属性,您可以在视图中显示该属性。在您的控制器方法中加载 Student 类型的数据并将其映射到 StudentViewModel
      • 能不能告诉我StudentViewModel的结构,让我试一试!如果你能帮助我,我真的很感激!
      • @KmrRaz, StudentViewModel 应该包含属性 int[] SelectedCourses 将绑定到所选课程的 ID,SelectList CourseList 是要显示的课程列表。然后在您看来使用@Html.ListBoxFor(m =&gt; m.SelectedCourses, Model.CourseList)Refer this example
      • 谢谢大家,你们帮助我很好地理解了这些事情!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 2016-03-16
      • 2013-08-04
      • 2012-12-10
      • 2016-09-26
      • 1970-01-01
      相关资源
      最近更新 更多