2015-11-02 86 views
2

從樣本代碼:爲什麼「建議在實體類中包含外鍵屬性」?

public class Student 
{ 
    public Student() { } 

    public int StudentId { get; set; } 
    public string StudentName { get; set; } 

    public int StdandardRefId { get; set; } 

    [ForeignKey("StandardRefId")] 
    public virtual Standard Standard { get; set; } 
} 

public class Standard 
{ 
    public Standard() 
    { 
     StudentsList = new List<Student>(); 
    } 
    public int StandardId { get; set; } 
    public string Description { get; set; } 

    public virtual ICollection<Student> Students { get; set; } 
} 

回答

4

想象一下,你要設置的關係的情況下,但你沒有Standard例如在內存中,唯一的你已經是StandardId。這將要求您首先在數據庫上執行查詢以檢索您需要的Standard實例,以便您可以設置Standard導航屬性。有時你可能沒有在內存中的對象,但你有權訪問該對象的關鍵值。隨着外鍵屬性,你可以簡單地使用密鑰值,而不依賴於在內存中該實例:

int standardId=2; 
//... 
student.StdandardRefId =standardId; 

綜上所述,白衣FK屬性,您將有兩個選項來設置的關係。

我的建議是當你需要創建一個新的Student與現有的Standard相關時,設置FK屬性而不是導航屬性。有場景中實體框架將Standard的狀態設置爲Added,即使它已經在數據庫中,這可能會導致在數據庫中的重複的存在。如果您只使用外鍵,則可以避免此問題。

0

通過指定虛標標準屬性,你告訴你的學生對象是關係到零級或一個標準的對象實體框架。

爲了(既然你指定的虛擬)實體框架自動檢索使用延遲加載這個對象,你也必須告訴它的對象究竟是如何與給它一個外鍵的註釋。當您嘗試首次訪問Standard屬性時,Entity Framework將自動嘗試在主鍵與外鍵匹配的上下文中查找匹配的Standard對象。

如果不指定關係,則可以手動檢索標準對象並使用屬性的設置訪問器。

相關問題