LINQ To Entities + Include + Anonymous type issue

前端 未结 3 2127
鱼传尺愫
鱼传尺愫 2020-12-03 17:54

Consider:

Class Client

Class Project

Class Ticket

Class Reply

Clients have a sub collection of projects, projects have a sub collecti

相关标签:
3条回答
  • 2020-12-03 18:04

    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.

    0 讨论(0)
  • 2020-12-03 18:08

    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
            });
    
    0 讨论(0)
  • 2020-12-03 18:12

    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.

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