Sum of hours (HH:MM) in Linq

点点圈 提交于 2020-02-24 06:12:31

问题


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:


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();


来源:https://stackoverflow.com/questions/58286139/sum-of-hours-hhmm-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!