【问题标题】:Translating SQL statement with dates to Linq-to-Sql for use with EF4将带有日期的 SQL 语句转换为 Linq-to-Sql 以用于 EF4
【发布时间】:2011-01-24 21:17:59
【问题描述】:

我有以下 SQL 命令:

SELECT        CONVERT(varchar, Logged, 103) AS Visited, COUNT(ID) AS Totals
FROM            tblStats
GROUP BY CONVERT(varchar, Logged, 103)
ORDER BY Visited DESC

我想将此转换为可与实体框架一起使用的 L2S 语句,但在使用日期时间类型时,我会遇到各种错误,具体取决于我尝试解决问题的方式。

方法:

var results = from s in db.Stats
      group s by (s.Logged.Date.ToString()) into Grp
      select new { Day = Grp.Key, Total = Grp.Count() };

错误:

LINQ to Entities 无法识别 方法'System.String ToString()' 方法,而这种方法不能 翻译成商店表达式。

方法:

var results = from s in db.Stats
              group s by (s.Logged.Date) into Grp
              select new { Day = Grp.Key, Total = Grp.Count() };

错误:

指定的类型成员“日期”是 在 LINQ to Entities 中不受支持。 只有初始化器、实体成员和 实体导航属性是 支持。

我需要什么语法才能使查询工作?

【问题讨论】:

    标签: asp.net-mvc linq-to-sql entity-framework-4


    【解决方案1】:

    尝试使用EntityFunctions.TruncateTime 方法:

    var results = from s in db.Stats
                  group s by EntityFunctions.TruncateTime(s.Logged) into Grp
                  select new { Day = Grp.Key, Total = Grp.Count() };
    

    【讨论】:

    • 这就是问题所在!谢谢。现在我有一个不同的问题,但我会为此设置一个新问题。
    【解决方案2】:

    您需要s.Logged.Date 中的Date 部分吗?

    你试过了吗:

    var results = from s in db.Stats
                  group s by (s.Logged) into Grp
                  select new { Day = Grp.Key, Total = Grp.Count() };
    

    我假设 Logged 是属性(表中的列)。

    编辑:你们速度很快。

    【讨论】:

    • 如果您不使用Date 部分,那么您将按完整日期时间分组,包括时间部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多