如何获取实体框架中特定时间之间的记录 [英] how to get the records between specific time in entity framework
问题描述
我想在早上7点到下午3点之间获取记录.如何编写相同的linq查询?
i want to fetch the records between 7am and 3pm . How to write linq query for the same?
代码
var items = Pirs.Where(a => !a.dataFrame.EndsWith("AAAAAAAAAAA=") && (fromDate == null || fromDate.Value.Date <= TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(a.timestamp), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).Date) && (toDate == null || toDate.Value.Date >= TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(a.timestamp), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")).Date) && (a.timestamp.Hour > 7 || a.timestamp.Hour < 15))
.GroupBy(a => a.dataFrame.Substring(a.dataFrame.Length - 12))
.Select(g => g.First()).OrderBy(a => a.timestamp);
样本数据
timestamp "2017-07-21T14:06:02.203Z"
推荐答案
问题的编写方式很难准确地理解您的要求,因此,我将为您提供实现目标的一般方法(我认为).
The way your question is written, it is difficult to understand exactly what you're asking, so I will give you a general way of achieving what (I think) you want.
假设您有一个课程,Foo
:
class Foo
{
public DateTime date { get; set; }
}
给出一个List<Foo>
,您可以在该列表中获得date
属性在某些小时之间的所有Foo
实例,如下所示:
Given a List<Foo>
, you can get all instances of Foo
in that list who's date
property is between certain hours like so:
var myList = new List<Foo>();
int startHour = 7; // 7am
int endHour = 15; // 3pm
var result = myList.Where(item => item.date.Hour >= startHour && item.date.Hour <= endHour);
result
枚举包含myList
中whos date
属性的Hour
字段在startHour
和endHour
之间的所有项目.
The result
enumerations contains all items in myList
whos date
property's Hour
field is between startHour
and endHour
inclusive.
需要注意的是,您可以使用扩展方法来大大简化此操作:
Something to note, you could use an extension method to greatly simplify this:
public static bool Between(DateTime input, int x, int y)
{
return (input.Hour => x && input.Hour <= y);
}
var result = myList.Where(item => item.date.Between(7, 15));
但是,您提到您使用的是第二种解决方案不兼容的Entity Framework,因为当您查询DbSet
时,该操作不是由程序执行的,而是由EF转换为SQL并由NET执行的.改为使用数据库提供程序.在查询中使用扩展方法需要先将所有内容加载到内存中,我不建议这样做.
However, you mentioned you were using Entity Framework, which this second solution is incompatible with, since when you query a DbSet
, that operation isn't performed by your program, but translated into SQL by EF and executed by the DB provider instead. Using an extension method in your query would require loading up everything into memory first, which I do not recommend.
这篇关于如何获取实体框架中特定时间之间的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!