Include with projection does not work

前端 未结 2 1879
盖世英雄少女心
盖世英雄少女心 2020-12-21 08:59

I have this query

    var test = context.Assignments
        .Include(a => a.Customer)
        .Include(a => a.Subscriptions)
        .Select(a => n         


        
相关标签:
2条回答
  • 2020-12-21 09:40

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

    0 讨论(0)
  • 2020-12-21 09:44

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

    0 讨论(0)
提交回复
热议问题