1

我有一個模型類EntityType'SelectListItem'沒有定義鍵。定義鍵此的EntityType

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

和我嘗試TI使用它作爲

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. 

請建議我在哪裏做錯了。

回答

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

我用selectitemlist,因爲當我編輯的學生,我需要一個列表框方含所有課程,我已經預先選擇哪個學生的課程已經選擇!我只是試圖通過EF檢索現在 ,你可以讓我知道你提到的上述代碼的哪個表結構,因爲我很困惑我將如何將CourseList映射到學生。 @dotnetom – KmrRaz 2014-11-23 16:46:25

+0

@KmrRaz爲了顯示數據庫中的數據,你應該創建一個特定的對象'StudentViewModel'。這是一個僅用於顯示目的的特定對象。在這裏有與SelectListItems,您可以顯示在視圖中的屬性。在你的控制器方法中加載'Student'類型的數據並將其映射到'StudentViewModel' – dotnetom 2014-11-23 16:53:09

+0

你可以讓我知道StudentViewModel的結構,以便我試試!我非常感謝你能幫助我! – KmrRaz 2014-11-23 16:58:36

6

添加[NotMapped]註釋List類

[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