我有这个查询
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上看到类似的问题,看起来你不能使用包含的投影。但是我没有找到解决问题的方法..任何人?
编辑:这是一个令人满意的投影加载,它比上面的例子更复杂,所以我不能理解我的生活是错的,谢谢。
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;
答案 0 :(得分:6)
这是by design。 Include
不适用于包含投影或自定义联接的方案。
答案 1 :(得分:5)
将客户添加到您的预测中:
var test = context.Assignments
.Select(a => new AssignmentWithSubscriptionCount
{
SubscriptionCount = a.Subscriptions.Count(),
Assignment = a,
Customer = a.Customer
});
var name = test.First().Customer.Name;
EF上下文可能会确保Assignment.Customer
自动填充。
修改强>
如果您不想或不能更改AssignmentWithSubscriptionCount
类,您也可以投影到匿名类型,然后将结果复制到内存中:
var test = context.Assignments
.Select(a => new
{
SubscriptionCount = a.Subscriptions.Count(),
Assignment = a,
Customer = a.Customer
});
test.ToList() // executes query
.Select(o =>
{
o.Assignment.Customer = o.Customer;
return new AssignmentWithSubscriptionCount
{
SubscriptionCount = o.SubscriptionCount,
Assignment = o.Assignment
}
});
另一种选择是明确加载(每个加载Assignment
需要一次额外的往返)。