【问题标题】:Linq2DB adding unnecessary statements to queryLinq2DB 添加不必要的语句进行查询
【发布时间】:2017-09-25 16:14:41
【问题描述】:

我正在尝试生成一个查询,以获取每个给定月份内出现日期的条目数。我希望生成的查询的 SQL 形式如下:

SELECT
DatePart(Year, [t1].[StartTime]) as Year,
DatePart(Month, [t1].[StartTime]) as Month,
Count(*) as 'Visits',
Sum([t1].[PageCount]) as 'Total Pageviews'
FROM
[MyDatabase] [t1]
GROUP BY
DatePart(Year, [t1].[StartTime]),
DatePart(Month, [t1].[StartTime])

我尝试了以下 Linq2DB 代码:

var query = from table in dataContext.MyDataContext(tablePath)
group table by new { table.StartTime.Year, table.StartTime.Month} into grp
select new { Month = grp.Key.Month, Year = grp.Key.Year,
TotalVisitors =   grp.Count(), 
TotalPageviews = grp.Sum(table2 => table2.PageCount) };

但是由此生成的 SQL 查询是

--  SqlServer.2008  --
SELECT
[t1].[StartTime],
Count(*) as [c1],
Sum([t1].[PageCount]) as [c2]
FROM
[MyDatabase] [t1]
GROUP BY
DatePart(Year, [t1].[StartTime]),
DatePart(Month, [t1].[StartTime]),
[t1].[StartTime]

为什么是 [t1].[StartTime] 而不是月份或年份?为什么它最后会按额外的 [t1].[StartTime] 分组?如何使用 Linq2DB 生成上面的 SQL 查询?

【问题讨论】:

    标签: linq linq-to-sql linq2db


    【解决方案1】:

    请对 Sql.AsSql 函数使用以下解决方法。我们正在努力解决这个长期存在的问题。

    var query = from table in dataContext.MyDataContext(tablePath)
    group table by new { Sql.AsSql(table.StartTime.Year), Sql.AsSql(table.StartTime.Month)} into grp
    select new { Month = Sql.AsSql(grp.Key.Month), Year = Sql.AsSql(grp.Key.Year),
    TotalVisitors =   grp.Count(), 
    TotalPageviews = grp.Sum(table2 => table2.PageCount) }; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多