Sum of hours (HH:MM) in Linq

Viewed 400

I am having "TimeClocked" in my database table in the format HH.mm and I want to sum all the "TimeClocked" using LINQ.

I have tried this aggregate function.

var data = _projectDbContext
    .Tasks
    .Where(x => x.Project.CompanyId == companyId && x.Status == true)
    .Select(e => TimeSpan.Parse(e.TimeClocked))
    .Aggregate(TimeSpan.FromMinutes(0), (total, next) => total + next)
    .ToString();

I am using EF Core 3.0.0. It's showing error like this.

Processing of the LINQ expression 'Aggregate<TimeSpan, TimeSpan>(
    source: Select<TaskEntity, TimeSpan>(
        source: Where<TaskEntity>(
            source: DbSet<TaskEntity>, 
            predicate: (x) => x.Project.CompanyId == (Unhandled parameter: __companyId_0) && x.Status == True), 
        selector: (e) => Parse(e.TimeClocked)), 
    seed: (Unhandled parameter: __p_1), 
    func: (total, next) => total + next)' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.

Any help will be grateful.

1 Answers

It happens due to restricted client evalution in EF Core 3 so you have to call AsEnumerable right before untranslatable expressions

var data = _projectDbContext
    .Tasks
    .Where(x => x.Project.CompanyId == companyId && x.Status == true)
    .AsEnumerable() // switches to LINQ to Objects
    .Select(e => TimeSpan.Parse(e.TimeClocked))
    .Aggregate(TimeSpan.FromMinutes(0), (total, next) => total + next)
    .ToString();
Related