我这里有同样的问题贴: 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.