tamim abweini
tamim abweini

Reputation: 431

EF core 3 nested group by after restricting client evaluation

After upgrading to entity framework core 3 the code below throws an exception when trying to get h.CreationDateTime.Hour, in EF core 2 this part was executed on the client. but now when EF Core 3.0 detects expressions that can't be translated anywhere else in the query, it throws a runtime exception.

var x = dbContext.data.GroupBy(c => c.CreationDateTime.Day)
                            .Select(d => new
                            {
                                day = d.Key,
                                hours = d.GroupBy(h => h.CreationDateTime.Hour).Select(h => new
                                {
                                    hour= h.Key,
                                    count = h.Count()
                                }).ToList()
                            }).ToList();

Is there a way this code can be rewritten to give the same output. any help is appreciated.

Upvotes: 1

Views: 5613

Answers (1)

Nagashree Hs
Nagashree Hs

Reputation: 853

Using .AsEnumerable() switches it to LINQ to object according to Microsoft docs. https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/

 var x = dbContext.data.GroupBy(c => c.CreationDateTime.Day)
                        .AsEnumerable()
                        .Select(d => new
                        {
                            day = d.Key,
                            hours = d.GroupBy(h => h.CreationDateTime.Hour).Select(h 
                            => new
                            {
                                hour= h.Key,
                                count = h.Count()
                            }).ToList()
                        }).ToList();

Upvotes: 4

Related Questions