2012-09-28 125 views
0

是否可以映射以下方案?實體框架代碼優先:實體分割

數據表

學生

+ ID:整數PK
+名稱:VARCHAR(200)

+ ID:整數PK
+學生ID:FK
+ CourseID:FK
+ EnrollmentDate:日期時間

課程

+ ID:整數PK
+名稱:VARCHAR(200)

我想的表來映射下面的實體。

public class Student 
{ 
    [Key] 
    public int ID {get;set;} 
    public string Name {get;set;} 
    public virtual ICollection<Class> Classes {get;set;} 
} 

public class Class 
{ 
[Key] 
public int ID {get;set;} 
public Student Student {get;set;} 
public DateTime EnrollmentDate {get;set;} 
public string Name {get;set;} // this comes from the Courses data table 
} 

回答

0

這應該是如何建立你所需要的FK關係:

public class Student 
{ 
    [Key] 
    public int StudentId {get;set;} 
    public string Name {get;set;} 
} 

public class Class 
{ 
    [Key] 
    public int ClassId {get;set;} 
    public DateTime EnrollmentDate {get;set;} 

    //foreign keys 
    public int CourseId {get;set;} 
    public string StudentId {get;set;} 

    //virtual constraint to link to referenced tables 
    public virtual Course Course {get;set;} 
    public virtual Student Student {get;set;} 
} 

public class Course 
{ 
    [Key] 
    public int CourseId {get;set;} 
    public string CourseName {get;set;} 
}