10

我正在使用 .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 查询或其他方法)?

4

2 回答 2

10

在这里使用EntityFunctions * 要简单得多:

var result =
    from query in DbManager.GetTable<SomeTableModel>()
    group query by EntityFunctions.TruncateTime(query.CreationDate)
    into list1
    select list1;

* Entity Framework 6 中的DbFunctions

于 2012-11-24T10:12:36.777 回答
5

更新答案: EntityFunctions已弃用。

警告 1“System.Data.Entity.Core.Objects.EntityFunctions”已过时:“此类已被 System.Data.Entity.DbFunctions 替换。” c:\users\liufa\documents\visual studio 2013\Projects\MatasMrLenderTest\Mvc5MobileApplication1\Controllers\CreditScoreController.cs 32 103 Mvc5MobileApplication1

现在是DbFunctions

using System.Data.Entity;

var result = DbManager.GetTable<SomeTableModel>()
.GroupBy(o => DbFunctions.TruncateTime(o.CreationDate))
于 2014-08-31T10:34:30.470 回答