How to group by DateTime.Date in EntityFramework

c# entity-framework entity-framework-6 linq

Question

I have this kind of gadget:

public class DeviceModel
{
    public DateTime Added { get;set; }
}

Additionally, I want to choose devices count, grouped byAdded date (not Time and Date, only Date). I cannot use my present implementation since linq cannot convertDateTime.Date to sql:

var result = (
    from device in DevicesRepository.GetAll()
    group device by new { Date = device.Added.Date } into g
    select new
        {
            Date = g.Key.Date,
            Count = g.Count()
        }
    ).OrderBy(nda => nda.Date);

How can this query be modified to work?

1
4
1/17/2014 12:56:15 PM

Accepted Answer

ZZZ_tmp
11
1/17/2014 12:51:43 PM

Popular Answer

Implement EntityFunctions. TruncateTime

var result = (
from device in DevicesRepository.GetAll()
group device by new { Date = EntityFunctions.TruncateTime(device.Added)} into g
select new
    {
        Date = g.Key.Date,
        Count = g.Count()
    }
).OrderBy(nda => nda.Date);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow