![](/img/trans.png)
[英]how to add a single record in to table which has foreign key using EF code first approach
[英]Using Database first approach in Entity framework, how to fetch the data from a single table only which has multiple foreign key relationship?
我在實體框架中使用數據庫優先方法。 我有兩個表,即人和角色表。 人員表有3列
角色表有2列
下面是這兩個表的自動生成的類以及外鍵關系。
public partial class Role
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Role()
{
this.People = new HashSet<Person>();
}
public int RoleId { get; set; }
public string RoleName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Person> People { get; set; }
}
public partial class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
public virtual Role Role { get; set; }
}
我使用以下代碼從“角色”表中檢索數據
public List<Role> GetRole()
{
var _context= new TestDBEntities();
List<Role> data = new List<Role>();
data = _context.Roles.ToList();
return data;
}
從角色表中檢索數據時,從角色表中檢索了所有數據,但同時檢索了人表數據。 其背后的原因一定是這兩個表之間的關系。 因此,我只想從“角色”表中獲取數據。 任何人都可以協助我如何僅從Person中獲取數據而不從Role表中獲取數據嗎?
顯示的代碼不會檢索相關數據,而是在其他一些代碼第一次訪問People
屬性時。 它可能是調試器變量窗口或一些序列化代碼。
此行為稱為“ 延遲加載” 。 可以通過多種方式禁用它,最簡單的方法是從導航屬性中刪除virtual
關鍵字。 在“代碼優先”中,您將直接在代碼中執行此操作,在EDMX設計器中,我猜必須有一些控制生成的屬性訪問器的屬性。 或使用“ 使用數據庫優先”方法線程有選擇地禁用延遲加載中介紹的技術。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.