How to group by DateTime.Date in EntityFramework

后端 未结 2 930
野的像风
野的像风 2020-12-02 02:15

I have a device model:

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

And i want to select devices count, grouped by <

2条回答
  •  心在旅途
    2020-12-02 02:40

    Well, according to this MSDN document, Date property is supported by LINQ to SQL and I'd assume that Entity Framework supports it as well.

    Anyway, try this query (notice that I'm using TruncateTime method in order to avoid resolving the date repeatedly):

    var result = from device in
                     (
                         from d in DevicesRepository.GetAll()
                         select new 
                         { 
                             Device = d, 
                             AddedDate = EntityFunctions.TruncateTime(d.Added) 
                         }
                     )
                 orderby device.AddedDate
                 group device by device.AddedDate into g
                 select new
                 {
                     Date = g.Key,
                     Count = g.Count()
                 };
    

    Hope this helps.

提交回复
热议问题