Grouping on day in linq to entities, ignoring time part

Here's the scenario:
  1. You are using LINQ to Entities
  2. In your data layer/SSDL whatever you want to call it, you are using the datetime data type.
  3. Now you want to group your data based on *only the date*. Let us say a daily report kind of view
  4. 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)
}

  1. 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

Popular Posts