Include with projection does not work

筅森魡賤 提交于 2019-12-18 08:55:34

问题


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;

回答1:


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;

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:

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).




回答2:


This is by design. Include is not for scenarios with projection or custom joins.



来源:https://stackoverflow.com/questions/7917348/include-with-projection-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!