2013-10-02 39 views
3

父實體簡單的列表我有兩個類:實體框架提取具有子實體

public class Profile 
{ 
    public int ProfileID { get; set; } 
    public string ProfileDescription { get; set; } 
    public int DisplayOrder { get; set; } 
    public virtual ICollection<Role> Roles { get; set; } 
} 

public class Role 
{ 
    public int RoleID { get; set; } 
    public string RoleDescription { get; set; } 
    public int DisplayOrder { get; set; } 
    public virtual ICollection<Profile> Profiles { get; set; } 
} 

用的DbContext

public DbSet<Profile> Profiles { get; set; } 
public DbSet<Role> Roles { get; set; } 

的輪廓是家長和匹配的角色集合是兒童 我有幾個類似的類。

我想只會有兩個必需的屬性

ProfileID, ProfileDescription 
查詢

SelectList(dbContext.Profiles.OrderBy(x => x.DisplayOrder).ToList(), "ProfileID", "ProfileDescription"); 

不具有帶回子角色

的開銷

選擇列表我不知道如何以一般方式做到這一點(返回父母沒有孩子)

+0

究竟是什麼問題得到只有兩個屬性配置文件列表? –

+0

查詢不僅返回配置文件,還返回匹配的角色。對於大型數據集來說,這是一個很大的開銷。 –

+1

由於您將導航屬性標記爲「虛擬」,實體框架只會在您訪問相關項目時獲取相關項目。如果你不這樣做,Entity Framework不會或至少不應該訪問它們。注意:在調試_will_中將實體添加到監視列表中會導致EF獲取相關項目。 –

回答

1

由於您將導航屬性標記爲virtual,實體框架只會在您訪問相關項目時獲取相關項目。如果你不這樣做,Entity Framework不會或至少不應該訪問它們。注意:在調試中將實體添加到監視列表中會導致EF獲取相關項目。

如果您在使用ToList()實現查詢之前添加Include(profile => profile.Roles),它將加載相關項目。

在MSDN上查看this article以獲取關於加載相關項目的更多信息。

3

您可以使用

var profiles = dbContext.Profiles 
     .Select(x => new { 
      ProfileID = x.ProfileID, 
      ProfileDescription = x.ProfileDescription 
     }).OrderBy(x => x.DisplayOrder).ToList(); 

SelectList profilelist = new SelectList(profiles, "ProfileID", "ProfileDescription"); 
+0

也謝謝你;這工作完美。我很幸運有兩個完整的答案,但可悲的是不能接受這兩個答案。 –

+0

@PeterSmith謝謝你的讚賞,如果你喜歡然後投我的答案 –

+0

我已經做了! :-) –