代码之家  ›  专栏  ›  技术社区  ›  chuckd

不支持TruncateTime实体框架函数的异常

  •  1
  • chuckd  · 技术社区  · 7 年前

    在我的linq expresion中尝试使用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调用到实体。

    at system.data.entity.dbfunctions.truncateTime(可以为空)`1 日期值)

    在 Yogabandy2017.服务.服务.YogaPaceService.<>c_uu显示Class9_1.b_uuu 1(YogaPaceEvent J) C:\users\chuckdawit\source\workspaces\yogabandy2017\yogabandy2017\yogabandy2017.services\services\yogaspaceservice.cs:line 二百五十六

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

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

    at System.Linq.Enumerable.ToList[t源](IEnumerable`1源)

    在 yogabandy2017.services.services.yogaspaceservice.getupcomingattendEventCounts(字符串 userid)在 C:\users\chuckdawit\source\workspaces\yogabandy2017\yogabandy2017\yogabandy2017.services\services\yogaspaceservice.cs:line 二百五十五

    在 yogabandy2017.controllers.scheduleController.getEventCountsForRattendCalendar()。 在里面 C:\users\chuckdawit\source\workspaces\yogabandy2017\yogabandy2017\yogabandy2017\controllers\scheduleController.cs:line 三百零九

    1 回复  |  直到 7 年前
        1
  •  1
  •   CodeNotFound dotnetstep    7 年前

    System.NotSupportedException:此函数只能从LINQ调用到实体。

    您有这个异常是因为 yogaProfile 变量不是 IQueryable Linq to实体使用它在服务器端执行查询。使变量成为 可查询的 您需要删除扩展方法 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对象。通过移除 第一个() 扩展方法并替换为 Take() 将执行Linq to Entities的扩展方法。