Grouping on day in linq to entities, ignoring time part
Here's the scenario:
- You are using LINQ to Entities
- In your data layer/SSDL whatever you want to call it, you are using the datetime data type.
- Now you want to group your data based on *only the date*. Let us say a daily report kind of view
- You try to execute the following
from Order order in context.Orders
group order by order.Modified.Date into groupedOrders
select new
{
TimeStamp = groupedOrders.Key,
OrderTotal = groupedOrders.Sum(order => order.OrderTotal)
}
- You see an error saying "Date is not supported by LINQ to Entities". You're out! No way around. There is indeed one.
I'd use this
from Order order in context.Orders
let onlyDate = EntityFunctions.TruncateTime(order.Modified)
group order by onlyDate into groupedOrders
select new
{
TimeStamp = groupedOrders.Key,
OrderTotal = groupedOrders.Sum(order => order.OrderTotal)
}
EntityFunctions exists in namespace System.Data.Objects so add the required references. It also has some other handy functions.
Comments