【问题标题】:Converting a datetime to date in iEF在 iEF 中将日期时间转换为日期
【发布时间】:2016-01-16 19:51:12
【问题描述】:

我有这个在 LinqPad 中按预期运行的 Linq 语句(使用 Linq to SQL),但是当我使用 EF 6 将它带入我的 C# 应用程序时,我收到一条错误消息,指出 cd.LogTimestamp.Date(在 GroupBy 语句中)不支持。我正在尝试将 datetime2 值转换为日期值以便按目的分组。

 helper.GetDbContext().SiteLog
     .Where( sl => sl.SiteId == 3 )
     .GroupBy( cd => new { cd.SiteId, cd.LogTimestamp.Date } )
     .Select( g => new DailyTraffic()
     {
         SiteId         = g.Key.SiteId,
         TrafficDate    = g.Key.Date,
         NewUsers       = g.Count( row => row.IsNewUser ),
         ReturningUsers = g.Count( row => row.IsReturningUser ),
         TotalUsers     = g.Count( row => row.IsNewUser ) + g.Count( row => row.IsReturningUser ),
         PageViews      = g.Count( row => row.IsPageView )
     } )
     .OrderBy( g => g.SiteId ).ThenBy( g => g.TrafficDate )
     .ToList();

在 EF 6 中是否有将datetime2 值转换为date 值的首选方法

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    使用此 QA (how to use entity framework to group by date not date with time) 作为指南,您将需要使用 EntityFunctions,以便您可以直接使用内置 SQL Server 函数,这当然意味着您的应用程序不会立即移植到其他数据库。

    .GroupBy( cd => new { cd.SiteId, EntityFunctions.TruncateTime( cd.LogTimestamp ) } )
    

    【讨论】:

    • 由于EntityFunctions.TruncateTime被标记为DeprecatedSystem.Data.Entity.DbFunctions.TruncateTime被替换。
    猜你喜欢
    • 2014-07-01
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 2014-06-07
    相关资源
    最近更新 更多