[英]Why “it is recommended to include foreign key property in the entity class”?
示例中的代碼:
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; }
}
想象一下一個場景,您想設置關系但內存中沒有Standard
實例,唯一的是StandardId
。 這將要求您首先在數據庫上執行查詢以檢索所需的Standard
實例,以便可以設置Standard
導航屬性。 有時您可能沒有對象在內存中,但是您確實可以訪問該對象的鍵值。 使用外鍵屬性,您可以簡單地使用鍵值,而不必依賴於實例是否在內存中:
int standardId=2;
//...
student.StdandardRefId =standardId;
總之,在FK屬性中,您將有兩個設置關系的選項。
我的建議是當您需要創建與現有Standard
相關的新Student
,設置FK屬性而不是Navigation屬性。 有場景中實體框架將設置Standard
的狀態, Added
,即使它已經存在於數據庫中,這可能會導致數據庫中的重復。 如果僅使用外鍵,則可以避免此問題。
通過指定虛擬Standard Standard屬性,您已告知Entity Framework您的Student對象與零個或一個Standard對象有關。
為了使Entity Framework使用延遲加載自動檢索此對象(由於您指定了virtual),還必須通過給它提供外鍵注釋來准確告知對象之間的關系。 當您第一次嘗試訪問Standard屬性時,Entity Framework將自動嘗試在其主鍵與您的外鍵匹配的上下文中找到匹配的Standard對象。
如果未指定關系,則可以手動檢索Standard對象並使用屬性的set訪問器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.