EF core 3 nested group by after restricting client evaluation

c# ef-core-3.0 entity-framework-core linq

Question

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.

1
1
10/3/2019 2:20:19 PM

Accepted Answer

Using .AsEnumerable() switches it to LINQ to object according to Microsoft docs. https://docs.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();
2
10/3/2019 3:53:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow