How to group by DateTime.Date in EntityFramework

后端 未结 2 916
野的像风
野的像风 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.

    0 讨论(0)
  • 2020-12-02 02:44

    Use 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);
    
    0 讨论(0)
提交回复
热议问题