简体   繁体   English

实体框架到 LINQ 日期搜索

[英]Entity framework to LINQ date search

I'm trying to build an EF to LINQ query where I need to sum a property by each day of the week - a sum of all records on Monday, then Tuesday, etc.我正在尝试构建一个 EF 到 LINQ 查询,我需要按一周中的每一天对属性求和 - 周一、周二等所有记录的总和。

Due to EF to LINQ inability to invoke C# methods, I can't get to the Date component (DateTime.Date) of the DateTime property I'm trying to filter on, so my current implementation looks like this:由于 EF 到 LINQ 无法调用 C# 方法,我无法访问我试图过滤的 DateTime 属性的 Date 组件 (DateTime.Date),所以我当前的实现如下所示:

 _monday = startDate.Date; //I know this is monday due to grid filters
 _tuesday = startDate.AddDays(1).Date;
 _wednesday = startDate.AddDays(2).Date;
...
 monday = context.Entites.Where(x=>x.Date == _monday).Sum(s => s...);
 tuesday = context.Entities.Where(x=>x.Date == _tuesday).Sum(s => s...);

However the data I'm receiving is not completely correct, and there are values assigned to wrong days.但是,我收到的数据并不完全正确,并且分配了错误日期的值。

Is there a way to make this query work with my current approach?有没有办法让这个查询与我目前的方法一起工作? The query is massive and full of other filters (that I know are not interfering with the date match) just like the dataset I'm working on, so using DbFunctions is not an option here (unless it does not impact performance at all).查询是大量的并且充满了其他过滤器(我知道不会干扰日期匹配),就像我正在处理的数据集一样,所以在这里使用 DbFunctions 不是一个选项(除非它根本不影响性能)。

You can do this as below您可以按以下方式执行此操作

_mondayStartTime = startDate.Date; //I know this is monday due to grid filters
_mondayEndTime = _mondayStartTime.AddDays(1).AddMilliseconds(-1);
 _tuesdayStartTime = startDate.AddDays(1).Date;
 _tuesdayEndTime = _tuesdayStartTime.AddDays(1).AddMilliseconds(-1);
...
 monday = context.Entites.Where(x=> _mondayStartTime <= x.Date && x.Date <= _mondayEndTime ).Sum(s => s...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM