包含投影不起作用 [英] Include with projection does not work

查看:181
本文介绍了包含投影不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个查询

    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上看到类似的问题,它看起来像你不能使用包含的投影。但我还没有找到解决问题的方法..任何人?

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;


推荐答案

将客户添加到您的预测中:

Add the customer to your projection:

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 自动填充。

The EF context will probably ensure that Assignment.Customer gets populated automatically.

编辑

如果您不想要或者无法更改 AssignmentWithSubscriptionCount 类,您也可以投影到匿名类型,然后将结果在内存中复制到此类中:

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:

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

另一种选择是明确加载(每次加载需要一次额外的往返分配虽然)。

Another option is explicite loading (requires one additional roundtrip per loaded Assignment though).

这篇关于包含投影不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆