Search code examples
c#mysqllinqpomelo-entityframeworkcore-mysql

LINQ Group By multiple columns and also count


I have the following LINQ code in my .NET Core application. I am using EF Core with Pomelo as driver for MySQL.

var journeyId = 5917;
var journey = Journeys.FirstOrDefault(j => j.JourneyId == journeyId);

var journeyEvents = from ad in AccelerometerData
                    join ae in AccelerometerEvents on ad.AccelerometerDataId equals ae
                        .AccelerometerData.AccelerometerDataId
                    where ad.Device.DeviceId == journey.Device.DeviceId && ae.TimeStamp >= journey.StartDateTime &&
                          ae.TimeStamp <= journey.EndDateTime
                    group ae by new
                    {
                        ae.EventType,
                        ae.Level
                    } into g
                    select new
                    {
                        EventType = new JourneyEventType { JourneyEventTypeId = g.Key.EventType },
                        Level = g.Key.Level,
                        Count = g.ToList().Count()
                    };

journey.JourneyEvents = journeyEvents.ToList();

When the code tries to run the last line, I get the following exception.

Could not parse expression 'g.ToList()': This overload of the method 'System.Linq.Enumerable.ToList' is currently not supported.

What am I missing?


Solution

  • Use g.Count() instead g.ToList().Count().

    var journeyEvents = from ad in AccelerometerData
                        join ae in AccelerometerEvents on ad.AccelerometerDataId equals ae
                            .AccelerometerData.AccelerometerDataId
                        where ad.Device.DeviceId == journey.Device.DeviceId && ae.TimeStamp >= journey.StartDateTime &&
                              ae.TimeStamp <= journey.EndDateTime
                        group ae by new
                        {
                            ae.EventType,
                            ae.Level
                        } into g
                        select new
                        {
                            EventType = new JourneyEventType { JourneyEventTypeId = g.Key.EventType },
                            Level = g.Key.Level,
                            Count = g.Count()
                        };
    
    journey.JourneyEvents = journeyEvents.ToList();