c# - Entity Framework Core 中 TimeSpan 的总和

标签 c# .net linq entity-framework-core

我有一个 View 模型用于在索引页上显示我的类(class)

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; }
}

我有获取所有类(class)的服务:

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

错误文本:

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.

我认为问题是 TimeSpan 的总和。对这个总结有什么建议吗?

最佳答案

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

关于c# - Entity Framework Core 中 TimeSpan 的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65524630/

相关文章:

c# - 我如何从后台线程访问 IServiceCollection

c# - 有没有更好的方法用另一个列表搜索列表

c# - 从大文本中解析数字,可能没有正则表达式(性能关键)

c# - 访问 Azure 上的自定义 STS(WCF 服务)时出错

.net - DB2 .NET 数据提供程序的 SQL1159 初始化错误,原因代码 7, token 9.5.0.DEF.2,SOFTWARE\IBM\DB2\InstalledCopies

c# - 创建数据表

c# - EF LINQ ToList 非常慢

xml - 如何使用xpath检索节点的第X个特定位置?

.net - 引用匿名类型属性

.net - 如何使用 LINQ 执行归并排序?