c# - LINQ to Entities Include() 不起作用

标签 c# linq entity-framework linq-to-entities entity-framework-4.1

以下 LINQ to Entities 查询(使用 EF 4.1 Code-First)应该基于 CampaignsUsers 创建 View 模型列表。我预先加载了每个广告系列的 Category 属性,以便每个广告系列的 Category 引用属性都填充了适当的数据。但似乎这种急切加载在某处丢失了,因此我无法访问以下类别:campViewModels[0].Campaign.Category。它始终为空。

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();  

为了解决这个问题,我更改了我的 View 模型定义并具有 CategoryText 属性并将其填充到我的查询中:

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

但是 我很想知道是什么阻止了类别的显式加载?

最佳答案

Include 在您投影到新类型、使用 joingroup by 时被忽略

关于c# - LINQ to Entities Include() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7532498/

相关文章:

c# - Entity Framework 在传递谓词时返回不同的结果

json - 我是如何解决 Json 序列化循环引用错误的?

c# - LocalDB (.mdf) 的连接字符串不适用于 WPF

c# - 在 ASP.net 中使用多对多关系

c# - 如何在asp.net自动完成文本框中用分号分隔文本框中的多个值

c# - 在运行时创建具有通用接口(interface)的通用类型

performance - 如何使用 LINQ 获得前两次出现?

c# - LINQ LEFT JOIN on Nullable<int>

c# - 指定的值包含无效的 HTTP header 字符

c# - 如何使用 linq-to-entities 构建类似 selectbyexample 的查询?