【问题标题】:Not supported exception with TruncateTime entity framework functionTruncateTime 实体框架函数不支持异常
【发布时间】:2018-10-31 19:23:19
【问题描述】:

尝试在我的 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:此函数只能从 LINQ to Entities 调用。

在 System.Data.Entity.DbFunctions.TruncateTime(Nullable`1 日期值)

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

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

在 System.Collections.Generic.List'1..ctor(IEnumerable`1 收藏)

在 System.Linq.Enumerable.ToList[TSource](IEnumerable`1 源)

在 YogaBandy2017.Services.Services.YogaSpaceService.GetUpcomingAttendEventCounts(字符串 用户 ID)在 C:\Users\chuckdawit\Source\Workspaces\YogaBandy2017\YogaBandy2017\Yogabandy2017.Services\Services\YogaSpaceService.cs:line 255

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

【问题讨论】:

    标签: c# entity-framework linq linq-to-entities


    【解决方案1】:

    System.NotSupportedException:此函数只能从 LINQ to Entities 调用。

    您有这个例外,因为yogaProfile 变量的结果不是IQueryable,Linq To Entities 使用它在服务器端执行查询。要使您的变量成为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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      相关资源
      最近更新 更多