【发布时间】:2021-04-08 00:00:21
【问题描述】:
我有一个视图模型用于在索引页面上显示我的课程
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; }
}
我有一个获取所有课程的服务:
...
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();
...
错误文本:
处理请求时发生未处理的异常。 InvalidOperationException:LINQ 表达式 'DbSet() .Where(c0 => EF.Property
(EntityShaperExpression: EntityType:课程 ValueBufferExpression:ProjectionBindingExpression: EmptyProjectionMember IsNullable: False , "CourseId") != null && object.Equals(objA: (object)EF.Property (EntityShaperExpression: EntityType: 课程 ValueBufferExpression:ProjectionBindingExpression: EmptyProjectionMember IsNullable: False , "CourseId"), objB: (object)EF.Property (c0, "CourseId"))) .Sum(c0 => c0.EpisodeTime.Ticks)' 无法翻译。要么重写 以可翻译的形式查询,或切换到客户评估 通过插入对“AsEnumerable”、“AsAsyncEnumerable”的调用,显式地 “ToList”或“ToListAsync”。看 https://go.microsoft.com/fwlink/?linkid=2101038 了解更多信息。
我认为问题是TimeSpan 的总和。对这个总结有什么建议吗?
【问题讨论】:
-
尝试用
c.CourseEpisodes.ToList().Sum替换c.CourseEpisodes.Sum。 -
如果您将
.AsEnumerable()放在.Select(之前,您会将查询数据拉到客户端,然后在客户端计算Select结果 - 您可能希望将.Select(c => new { c.CourseId, c.CourseTitle, c.CourseImageName, c.CoursePrice })放在Include之前进行过滤数据拉到客户端。
标签: c# .net linq entity-framework-core