开发者

LINQ to Entities Include() does not work

开发者 https://www.devze.com 2023-04-06 20:27 出处:网络
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

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 dat开发者_StackOverflowa. 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消