2013-10-16 127 views
1

所以基本上我有一個學生表,它持有一個Person表所需的外鍵。我已經建立了我的班如下:實體框架1-1..1關係沒有按預期運行

class Person 
{ 
    public int PersonID { get; set; } 
    public string Phone_Number { get; set; } 
    public string Email { get; set; } 
    public string Address { get; set; } 
    public string First_Name { get; set; } 
    public string Last_Name { get; set; } 

    //navigation properties 
    public virtual Student Student { get; set; } 

    public override string ToString() 
    { 
     return Last_Name + ", " + First_Name; 
    } 
} 

class Student 
{ 
    public int StudentID { get; set; } 
    public DateTime Dob { get; set; } 

    public int PersonID { get; set; } 
    public int Student_TypeID { get; set; } 

    //navigation properties 
    [Required] 
    public virtual Person Person { get; set; } 
} 

每當我嘗試下面添加一個新的學生,外鍵對人保持在0:

Student student = new Student 
{ 
    Dob = dpStudentDob.Value, 
    Student_TypeID = (rdoStudentRegular.Checked) ? 1 : 2, 
    Person = new Person 
    { 
     First_Name = txtStudentFirstName.Text, 
     Last_Name = txtStudentLastName.Text, 
     Address = txtStudentAddress.Text, 
     Email = txtStudentEmail.Text, 
     Phone_Number = txtStudentPhoneNum.Text 
    } 
}; 

using (var context = new MusicSchoolDB()) 
{ 
    context.Students.Add(student); 
    context.SaveChanges(); 
} 

不管有多少次我想補充一個學生,人的外鍵保持在0。 。

由於提前, 的J EF代碼

+0

此外,觀看在SSMS數據庫圖表時,關係已經形成正確。 – JohnW

回答

0

默認行爲首先是名字這樣你的外鍵:Person_ID。你打電話給你的財產PersonID,所以EF沒有意識到這應該是你的外鍵。在數據庫的內部,創建了一個名爲Person_ID的列,該列僅在您的模型中未映射。

使用數據的註釋,你可以明確的告訴EF你的外鍵屬性是:

public int PersonID { get; set; } 

[ForeignKey("PersonID")] 
public virtual Student Student { get; set; } 
+0

根據http://msdn.microsoft.com/en-US/data/jj679962外鍵的約定不包含下劃線? – JohnW

0

試試這個,

class Student 
    { 
     [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
     public int StudentID { get; set; } 
     public DateTime Dob { get; set; } 

     [ForeignKey("Person")] 
     [Key] 
     public int PersonID { get; set; } 
     public int Student_TypeID { get; set; } 

     //navigation properties 
     public virtual Person Person { get; set; } 
    } 

class Person 
    { 
     [Key] 
     public int PersonID { get; set; } 
     public string Phone_Number { get; set; } 
     public string Email { get; set; } 
     public string Address { get; set; } 
     public string First_Name { get; set; } 
     public string Last_Name { get; set; } 

     //navigation properties 
     public virtual Student Student { get; set; } 

     public override string ToString() 
     { 
      return Last_Name + ", " + First_Name; 
     } 
    }