[英].NET Entity Framework code-first: navigation properties are not loaded
在我的應用程序中,我有許多實體。
其中兩個是Person 和Company,它們是多對多的關系。
因此,在我的代碼中,我有一個 Person 類,其中包含對公司集合 (ICollection) 的引用,以及一個包含對人員集合的引用的 Company 類。 (ICollection)。
使用第一個代碼方法,正確生成了數據庫。 共有三個表:人員、公司和人員公司。
在 PeopleCompanies 表中,我有一條記錄,它應該在確定的人員和其他確定的公司之間創建關聯,如下圖所示。
http://s27.postimg.org/xnkz3j94j/DBPrint.png
那么,我的問題是什么?
在我的業務邏輯中,我需要知道哪些人與確定的公司相關聯,但公司類的導航屬性仍然為空:ICollection.Count() -----> 0
實際上,正如您在上圖中所看到的,只有一個人與該公司相關聯。
我需要導航屬性!
有人可以幫忙嗎?
DbContext 的代碼如下。 謝謝!
public class EnterpriseDataContext : DbContext
{
public EnterpriseDataContext(string connString) : base(connString)
{
}
#region CRM Module
public DbSet<Category> Categories { get; set; }
public DbSet<City> Cities { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<CompanyNote> CompanyNotes { get; set; }
public DbSet<Country> Countries { get; set; }
public DbSet<Lead> Leads { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<PersonNote> PersonNotes { get; set; }
public DbSet<Sector> Sectors { get; set; }
#endregion
}
我的通靈調試能力告訴我延遲加載已啟用並且您沒有使用正確的包含。
首先,您需要確保您有以下 using 語句
using System.Data.Entity
然后使用.Include()
加載您的人員。
var myEnterpriseDataContext = new EnterpriseDataContext("insert connection string here");
myEnterpriseDataContext.Companies
.Include(c => c.People)
//.Rest Of Query
注意:對於僅在執行查詢時訪問的字段,您不需要包含。 IE
myEnterpriseDataContext.Companies
.Select(c => new CompanyViewModel(){People = c.People});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.