TruncateTime entity framework 函数不支持异常

Not supported exception with TruncateTime entity framework function

在我的 linq 表达式中尝试使用 TruncateTime() 时出现异常 我不确定为什么?

这是我的声明

var yogaProfile = dbContext.YogaProfiles.Where(i => i.ApplicationUserId == userId).First();

var yogaEvents = yogaProfile.RegisteredEvents.Where(j => 
       (j.EventStatus == YogaSpaceEventStatus.Active || j.EventStatus == YogaSpaceEventStatus.Completed)
       && DbFunctions.TruncateTime(j.UTCEventDateTime) > DbFunctions.TruncateTime(yesterday)
       && DbFunctions.TruncateTime(j.UTCEventDateTime) <= DbFunctions.TruncateTime(todayPlus30)
       ).ToList();

这里是个例外

System.NotSupportedException: This function can only be invoked from LINQ to Entities.

at System.Data.Entity.DbFunctions.TruncateTime(Nullable`1 dateValue)

at YogaBandy2017.Services.Services.YogaSpaceService.<>c__DisplayClass9_1.b__1(YogaSpaceEvent j) in C:\Users\chuckdawit\Source\Workspaces\YogaBandy2017\YogaBandy2017\Yogabandy2017.Services\Services\YogaSpaceService.cs:line 256

at System.Linq.Enumerable.WhereListIterator`1.MoveNext()

at System.Collections.Generic.List'1..ctor(IEnumerable`1 collection)

at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

at YogaBandy2017.Services.Services.YogaSpaceService.GetUpcomingAttendEventCounts(String userId) in C:\Users\chuckdawit\Source\Workspaces\YogaBandy2017\YogaBandy2017\Yogabandy2017.Services\Services\YogaSpaceService.cs:line 255

at YogaBandy2017.Controllers.ScheduleController.GetEventCountsForAttendCalendar() in C:\Users\chuckdawit\Source\Workspaces\YogaBandy2017\YogaBandy2017\YogaBandy2017\Controllers\ScheduleController.cs:line 309

System.NotSupportedException: This function can only be invoked from LINQ to Entities.

您出现此异常是因为 yogaProfile 变量的结果不是 Linq To Entities 在服务器端执行查询所使用的 IQueryable。要使您的变量成为 IQueryable,您需要删除最后在查询中使用的扩展方法 First(),并将其替换为 Take(1)

所以不用

var yogaProfile = dbContext.YogaProfiles.Where(i => i.ApplicationUserId == userId).First();

你应该有这个:

var yogaProfile = dbContext.YogaProfiles.Where(i => i.ApplicationUserId == userId).Take(1);

请注意,当您对变量执行 Linq 时,您正在处理 Linq To Objects 的第一条语句。通过删除 First() 扩展方法并将其替换为 Take() 扩展方法,您将执行 Linq To Entites。