user3311498
user3311498

Reputation: 3

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.

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:

 _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).

Upvotes: 0

Views: 103

Answers (1)

Sowmyadhar Gourishetty
Sowmyadhar Gourishetty

Reputation: 1878

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...);

Upvotes: 1

Related Questions