carens
carens

Reputation: 319

How to get average date difference in PostgreSQL using EF Core 3

Using npgsql, EF Core 3 and a PostgreSQL database, I am trying to write the following SQL query in LINQ.

SQL:

SELECT date("EndDate"), avg("EndDate"-"StartDate") as avg_time
FROM trip
group by date("EndDate")

LINQ:

var q = from trip in _context.Trips
        group trip by trip.EndDate.Date into tripGroup
        select new { date = tripGroup.Key, avg_time_mins = tripGroup.Average(tg => (tg.EndDate - tg.StartDate).TotalMinutes) };

I tried with TotalMinutes, because .Average( ) does not seem to take a TimeSpan. All efforts ended up with a runtime exception stating that this construct is not supported and suggesting to rewrite the query.

Upvotes: 0

Views: 1087

Answers (1)

hanan
hanan

Reputation: 1880

If u want to TimeSpan as average using Linq(that what I understand from question) first u have to understand average will be done in memory.

var groups = await _context.Trips.GroupBy(trip =>trip.EndDate.Date).ToArrayAsync() // load Them in memory

var q = groups.Select(group=> {
    var timeSpans = group.Select(trip=>trip.EndDate - trip.StartDate);
    var avg = GetAverage(timeSpans)
    return new {group.key, avg }
}).ToArray()


TimeSpan GetAverage(IEnumerable<TimeSpan> timeSpans){
 var average= timeSpans.Average(x => x.TotalMilliseconds)
 return TimeSpan.FromMilliseconds(average);
} 

Upvotes: 1

Related Questions