how to use entity framework to group by date not date with time

c# entity-framework linq

Question

my code:

//get data
var myData = from log in db.OperationLogs
              group log by log.CreateTime.Date  into g
              orderby g.Key
              select new { CreateTime = g.Key, Count = g.Count() };

this code will throw an exception like entity framework does not support get Date operation. because log.createtime both have date and time, i want to group by date, how should i do

1
25
8/8/2019 5:09:36 AM

Accepted Answer

Use EntityFunctions.TruncateTime Method (Nullable<DateTime>). It will be transalated into TRUNCATETIME() TSQL function in generated SQL query, which does what you need:

Returns the expression, with the time values truncated.

So your code should be as follows:

//get data
var myData = from log in db.OperationLogs
             group log by EntityFunctions.TruncateTime(log.CreateTime) into g
             orderby g.Key
             select new { CreateTime = g.Key, Count = g.Count() };
50
1/7/2014 6:10:55 AM

Popular Answer

     var result = from s in entitiesModel.TvysFuelTankDatas
                           orderby s.Datetime ascending
                           group s by new { y = s.Datetime.Year, m = s.Datetime.Month + "/", d = s.Datetime.Day + "/" } into g
                           select new WellDrillData { Date = Convert.ToDateTime(g.Key.d.ToString() + g.Key.m.ToString() + g.Key.y.ToString()), Depth = (double)g.Sum(x => x.Difference) };

              List<WellDrillData> dailyFuelConsumptions = result.ToList();


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