Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities Include() does not work

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?

like image 565
Kamyar Avatar asked Sep 23 '11 17:09

Kamyar


1 Answers

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

like image 165
Aducci Avatar answered Sep 28 '22 07:09

Aducci