Linq when using GroupBy, Include is not working

为君一笑 提交于 2019-11-27 19:22:34

Include demands that the shape of the query doesn't change. It means that your query must return IQueryable<Match>. GroupBy operator is probably considered as shape changing because it returns IQueryable<IGrouping<TKey, TSource>>. Once the shape of the query changes all Include statements are omitted. Because of that you cannot use Include with projections, custom joins and groupings.

As a workaround you can execute grouping in Linq-to-objects:

var matches = context.matches
                     .Include("Official")
                     .Include("Slot")
                     .Include("MatchParticipants.Team")
                     .Include("Category.Tournament")
                     .Where(m => m.Category.Tournament.TournamentId == tournamentId)
                     .ToList()
                     .GroupBy(m => m.Category);

Edit: As mentioned in comments and in other answer, this is very dangerous workaround which can lead to performance problems. It pulls all records from database to the application and makes the aggregation in the app. It can work in same cases but it is definitely not applicable as generic solution.

In this special case, when your GroupBy is the latest operator, this query works good... But IMHO answer above is the worst answer for beginer, because it causes really badly optimized query when your GroupBy is not executed right after it, but is followed by some other statement (Where, Select...).

var ctx = new MyDataContext(); // Please use "using"
var result = ctx.SomeTable
                //.Include(ah => ah.IncludedTable) // DO NOT PUT IT HERE
                .Where(t => t.IsWhateverTrue)
                .GroupBy(t => t.MyGroupingKey)
                .Select(gt => 
                    gt.OrderByDescending(d => d.SomeProperty)
                        .FirstOrDefault(ah => ah.SomeAnotherFilter))
                .Include(ah => ah.IncludedTable) // YES, PUT IT HERE
                .ToList(); // Execute query here
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!