包含投影不起作用
我有这个查询
var test = context.Assignments
.Include(a => a.Customer)
.Include(a => a.Subscriptions)
.Select(a => new AssignmentWithSubscriptionCount { SubscriptionCount = a.Subscriptions.Count(), Assignment = a })
.ToList();
var name = test.First().Assignment.Customer.Name;
它无法急切地加载客户,我在 stackoverflow 上看到了类似的问题,看起来你不能将投影与 include 一起使用。但我还没有找到解决我的问题的方法..有人吗?
编辑:这是一个可以工作的投影的急切负载,它比上面的示例更复杂,所以我一生都无法理解出了什么问题,谢谢。
var test = context.PublicationStateGroups
.Include(p => p.PublicationStates.Select(ps => ps.AllowedPublicationStateActions.Select(aps => aps.PublicationStateAction)))
.Select(psg => new StateAndGroupInfo
{
ShowReport = psg.PublicationStates.Any(p => p.PublicationStateReportTypeId.HasValue),
Actions = psg.PublicationStates.SelectMany(state => state.AllowedPublicationStateActions)
.Select(a => a.PublicationStateAction)
.Distinct()
}).ToList();
var eagerTest = test.First().Actions.First().Name;
I have this query
var test = context.Assignments
.Include(a => a.Customer)
.Include(a => a.Subscriptions)
.Select(a => new AssignmentWithSubscriptionCount { SubscriptionCount = a.Subscriptions.Count(), Assignment = a })
.ToList();
var name = test.First().Assignment.Customer.Name;
It failes to eagerly load Customer, I've seen similar problems here on stackoverflow and it looks like you cant use projections with include. But I have not found a solution to my problem.. Anyone?
edit: Here is a eager load with projection that work, its more complex than the example above so I cant for my life understand whats wrong, thanks.
var test = context.PublicationStateGroups
.Include(p => p.PublicationStates.Select(ps => ps.AllowedPublicationStateActions.Select(aps => aps.PublicationStateAction)))
.Select(psg => new StateAndGroupInfo
{
ShowReport = psg.PublicationStates.Any(p => p.PublicationStateReportTypeId.HasValue),
Actions = psg.PublicationStates.SelectMany(state => state.AllowedPublicationStateActions)
.Select(a => a.PublicationStateAction)
.Distinct()
}).ToList();
var eagerTest = test.First().Actions.First().Name;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是设计。
Include
不适用于具有投影或自定义联接的场景。This is by design.
Include
is not for scenarios with projection or custom joins.将客户添加到您的投影中:
EF 上下文可能会确保自动填充
Assignment.Customer
。编辑
如果您不想或无法更改
AssignmentWithSubscriptionCount
类,您还可以投影到匿名类型,然后将内存中的结果复制到此类中:另一种选择是显式加载(但每个加载的
Assignment
需要一次额外的往返)。Add the customer to your projection:
The EF context will probably ensure that
Assignment.Customer
gets populated automatically.Edit
If you don't want or can't change the
AssignmentWithSubscriptionCount
class you can also project into an anonymous type and then copy the result in memory into this class:Another option is explicite loading (requires one additional roundtrip per loaded
Assignment
though).