.NET的LINQ to实体组按日期(天) [英] .NET LINQ to entities group by date (day)

查看:243
本文介绍了.NET的LINQ to实体组按日期(天)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有同样的问题贴: LINQ使用.date

然而,得到的答案是不是100%正确。它的工作原理在所有情况下,除非不同的时区的使用。当不同的时区时,它也对基时区。为什么? 我设法通过多种实体的职能绕过这一点。

  INT localOffset = Convert.ToInt32(
    TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes);

VAR的结果=(
    从perfEntry在db.entry
    哪里 (....)
    选择新{
        perfEntry.Operation,perfEntry.Duration,
        本地时间= EntityFunctions.AddMinutes(perfEntry.Start,
            localOffset  -  EntityFunctions.GetTotalOffsetMinutes(
                perfEntry.Start))
    }
).GroupBy(X =>新建{
    时间= EntityFunctions.TruncateTime(
        EntityFunctions.CreateDateTime(x.localTime.Value.Year,
            x.localTime.Value.Month,x.localTime.Value.Day,0,0,0)),
    x.Operation}
).OrderByDescending(一个=> a.Key)。
选择(G =>新建{
    时间= g.Key.Time,
    ...
});
 

有没有人在那里谁知道如何做到这一点的正确方法?这code是那么难看,可能效率非常低。

更新(警告):
我也意识到了功能EntityFunctions.CreateDateTime从错误受到影响。它不兼容闰年,比如今年。 2012年2月29日将抛出异常。

解决方案

您可以使用UTC日期时间和之后trunkate的时间。

I have the same problem posted here: LINQ to Entities group-by failure using .date

However, the answer is not 100% correct. It works in all cases except when different timezones are used. When different timezones are used, it also groups on timezones. Why? I managed to bypass this by using many entity functions.

int localOffset= Convert.ToInt32(
    TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalMinutes);

var results = (
    from perfEntry in db.entry
    where (....)
    select new { 
        perfEntry.Operation, perfEntry.Duration, 
        localTime = EntityFunctions.AddMinutes(perfEntry.Start, 
            localOffset - EntityFunctions.GetTotalOffsetMinutes(
                perfEntry.Start)) 
    }
).GroupBy(x => new { 
    Time = EntityFunctions.TruncateTime(
        EntityFunctions.CreateDateTime(x.localTime.Value.Year,
            x.localTime.Value.Month, x.localTime.Value.Day, 0, 0, 0)),
    x.Operation }
).OrderByDescending(a => a.Key).
Select(g => new {
    Time = g.Key.Time,
    ...
});

Is there someone out there who knows how to do this the proper way? This code is so ugly and probably very inefficient.

UPDATE (warning):
I also realised that the function EntityFunctions.CreateDateTime suffers from a bug. Its not compatible with leap years, such as this year. 29 feb 2012 will throw an exception.

解决方案

You can use UTC DateTime and trunkate the time after it.

这篇关于.NET的LINQ to实体组按日期(天)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆