5

The following LINQ to Entities query (using EF 4.1 Code-First), is supposed to create a list of viewmodels based on Campaigns and Users. I have eager-loaded Category property of each campaign so that each campaign should have its Category reference property filled with appropriate data. But it seems like this eager-loading is lost somewhere, thus I cannot access categories like: campViewModels[0].Campaign.Category. It's always null.

var campViewModels = ctx.Campaigns
.Include(c => c.Category)
.Where(c => c.Title.Contains(searchText)).Join(
    ctx.Users,
    c => c.CampaignId,
    u => u.CampaignId,
    (c, u) => new {c, u})
    .GroupBy(cu => cu.c)
    .Select(g => new CampaignViewModel { Campaign =  g.Key, MemberCount=g.Count()})
    .OrderByDescending(vm => vm.MemberCount)
    .Skip(pageIndex)
    .Take(pageSize)
    .ToList();  

For workaround this problem, I have changed my viewmodel definition and to have CategoryText property and filled it in my query:

Select(g => new CampaignViewModel { Campaign =  g.Key, MemberCount=g.Count(), CategoryText = g.Key.Category.Title})  

But I'm curious to find out what prevented the explicit loading of categories?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Kamyar
  • 18,639
  • 9
  • 97
  • 171
  • 1
    Combination of `Include` and a projection is a problem: http://stackoverflow.com/questions/4474951/entity-framework-include-is-not-working/4475504#4475504 (especially the links in the answer) – Slauma Sep 23 '11 at 17:15

1 Answers1

11

Include is ignored when you project to a new type, use a join, or a group by

Aducci
  • 26,101
  • 8
  • 63
  • 67