我正在使用 .NET 和实体框架。我想按没有时间部分的日期对表格进行分组。
我有课:
public sealed class QueryItem {
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
以及方法(我使用的是 BLToolkit,如果你想知道什么是 DbManager):
protected override IQueryable<QueryItem> InitiateQuery() {
return
from query in DbManager.GetTable<SomeTableModel>()
group query by new { Year = query.CreationDate.Year, Month = query.CreationDate.Month, Day = query.CreationDate.Day }
into list1
select new QueryItem {Year = list1.Key.Year, Month = list1.Key.Month, Day = list1.Key.Day};
}
在这个方法中 linq 翻译成这个 SQL 查询:
SELECT
[query].[CreationDate]
FROM
[SomeDatabase.SomeTable] [query]
GROUP BY
DatePart(Year, [query].[CreationDate]),
DatePart(Month, [query].[CreationDate]),
DatePart(Day, [query].[CreationDate]),
[query].[CreationDate]
这是错误的查询,因为它不仅仅按日期分组。
但是如果我使用这段代码(它不可用,我需要返回一个类对象):
var result =
from query in DbManager.GetTable<SomeTableModel>()
group query by new { Year = query.CreationDate.Year, Month = query.CreationDate.Month, Day = query.CreationDate.Day }
into list1
select list1;
会被翻译成这样:
SELECT
[t1].[c1] as [c11],
[t1].[c2] as [c21],
[t1].[c3] as [c31]
FROM
(
SELECT
DatePart(Year, [selectParam].[CreationDate]) as [c1],
DatePart(Month, [selectParam].[CreationDate]) as [c2],
DatePart(Day, [selectParam].[CreationDate]) as [c3]
FROM
[SomeDatabase.SomeTable] [selectParam]
) [t1]
GROUP BY
[t1].[c1],
[t1].[c2],
[t1].[c3]
这是正确的查询。
我想实体框架试图优化我的查询或类似的东西,这就是我得到错误查询的原因。
我对吗?我是否以正确的方式做这件事?我应该怎么做(可能使用直接 SQL 查询或其他方法)?