Sum of TimeSpan in Entity Framework Core

Viewed 780

I have a View Model for showing my course on the index page

public class ShowCourseListItemViewModel
{
    public int CourseId { get; set; }
    public string Title { get; set; }
    public string ImageName { get; set; }
    public int Price { get; set; }
    public TimeSpan TotalTime { get; set; }
}

and I have a service for Get All Courses:

...
return result.Include(e => e.CourseEpisodes).Select(c => new ShowCourseListItemViewModel()
{
    CourseId = c.CourseId,
    Title = c.CourseTitle,
    ImageName = c.CourseImageName,
    Price = c.CoursePrice,
    TotalTime = new TimeSpan(c.CourseEpisodes.Sum(e => e.EpisodeTime.Ticks)) <== Error is Here
}).Skip(skip).Take(take).ToList();
...

Error Text:

An unhandled exception occurred while processing the request. InvalidOperationException: The LINQ expression 'DbSet() .Where(c0 => EF.Property<Nullable>(EntityShaperExpression: EntityType: Course ValueBufferExpression: ProjectionBindingExpression: EmptyProjectionMember IsNullable: False , "CourseId") != null && object.Equals( objA: (object)EF.Property<Nullable>(EntityShaperExpression: EntityType: Course ValueBufferExpression: ProjectionBindingExpression: EmptyProjectionMember IsNullable: False , "CourseId"), objB: (object)EF.Property<Nullable>(c0, "CourseId"))) .Sum(c0 => c0.EpisodeTime.Ticks)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

I think problem is Sum of TimeSpan. Any suggestion on this summation?

2 Answers
        return result.Include(e => e.CourseEpisodes).AsEnumerable()
            .Select(c => new ShowCourseListItemViewModel()
            {
                CourseId = c.CourseId,
                Title = c.CourseTitle,
                ImageName = c.CourseImageName,
                Price = c.CoursePrice,
                TotalTime = new TimeSpan(c.CourseEpisodes.ToList().Sum(e => e.EpisodeTime.Ticks))
            }).Skip(skip).Take(take).ToList();

You need to execute the query by calling a method such as ToList before doing the Select since EF won't know how to convert that part to SQL. Try this:

return result.Include(e => e.CourseEpisodes).Skip(skip).Take(take).ToList()
.Select(c => new ShowCourseListItemViewModel()
{
    CourseId = c.CourseId,
    Title = c.CourseTitle,
    ImageName = c.CourseImageName,
    Price = c.CoursePrice,
    TotalTime = new TimeSpan(c.CourseEpisodes.Sum(e => e.EpisodeTime.Ticks))
});
Related