14

Consider:

Class Client

Class Project

Class Ticket

Class Reply

Clients have a sub collection of projects, projects have a sub collection of tickets and tickets have a sub collection of replies.

var data = ctx.Set<Ticket>().Include(p => p.Client).
Select(p => new { Ticket = p, LastReplyDate = p.Replies.Max(q => q.DateCreated)});

Doesn't work. Neither project nor client are loaded when selecting data this way.

I know how to make it work. My question is why doesn't it work like this?

3 Answers 3

15

As Ladislav mentioned, Include only works if you select the Ticket entity directly. Since you're projecting other information out, the Include gets ignored.

This should provide a good work-around:

var data = ctx.Set<Ticket>()
    .Select(p => new 
         { 
             Ticket = p, 
             Clients = p.Client,
             LastReplyDate = p.Replies.Max(q => q.DateCreated)
         });

First of all, each Ticket's Clients will be accessible directly from the Clients property on the anonymous type. Furthermore, Entity Framework should be smart enough to recognize that you have pulled out the entire Client collection for each Ticket, so calling .Ticket.Client should work as well.

3
  • Thanks. That is also the solution i thought of.
    – Jeroen
    Aug 24, 2011 at 11:29
  • I should point out to anyone reading this solution that EF doesn't magically populate the .Ticket.Client navigation property with entities returned with this projection, so accessing clients through the Ticket object will query the database again. Feb 13, 2018 at 10:53
  • @PedroPedrosa: This may have changed in more recent versions of EF. At the time I wrote this answer, EF actually did figure out that we'd materialized all of that ticket's Clients, and so it eagerly loaded that data into that property. Feb 13, 2018 at 17:15
8

Because Include works only if you select entities directly. Once you do the projection Include is ignored. I will not tell you why but it simply works this way.

2
  • Do you think Microsoft plans to change that ?
    – billy
    Oct 20, 2012 at 20:36
  • 1
    plus1 I will not tell you why but it simply works this way. Nov 2, 2016 at 12:24
2

Another possibility is to use StriplingWarrior's solution but then cleanse the intermediate data from the final result:

var data = ctx.Set<Ticket>()
    .Select(p => new 
        { 
            Ticket = p, 
            Clients = p.Client,
            LastReplyDate = p.Replies.Max(q => q.DateCreated)
        })
    .AsEnumerable()
    .Select(p => new
        {
            Ticket = p.Ticket, 
            LastReplyDate = p.LastReplyDate
        });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.