Linq Grouping失去了子实体

时间:2013-03-26 18:10:31

标签: asp.net-mvc-3 entity-framework asp.net-mvc-4 ef-code-first

我有以下查询:

        var _customers = (from c in _db.UserProfiles.Include(x=>x.ParentCompanies).Include(x=>x.cProfile).Include(x=>x.cProfile.PhoneNumbers).Include(x=>x.cProfile.Addresses)
                          where (c.ParentCompanies.Any(pc => pc.CompanyUsers.Any(cu => cu.UserName == userName)) && c.cProfile != null)
                          group c by c.FirstName.Substring(0, 1).ToUpper() into customerGroup
                          select new ContactsViewModel
                          {
                              FirstLetter = customerGroup.Key,
                              Customers = customerGroup
                          }).OrderBy(letter => letter.FirstLetter);

如果我取出group,它会很好地包含所有孩子(parentCompanies, cProfile, ...),只要我放回group就会失去所有孩子。我该如何解决这个问题?

更新

我想我还应该包含我用来放置结果的视图模型。

public class ContactsViewModel
{
    public string FirstLetter { get; set; }
    public IEnumerable<UserProfile> Customers { get; set; }
}

1 个答案:

答案 0 :(得分:1)

Include仅适用于查询结果中的项目(即最终投影),并且不能包含更改Include和最外层操作(例如GroupBy())之间结果类型的操作

http://wildermuth.com/2008/12/28/Caution_when_Eager_Loading_in_the_Entity_Framework

如果你想加载,请进行客户端分组(即枚举查询然后在结果上调用GroupBy方法)