Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 227
Arthas Avatar asked Jan 07 '14 03:01

Arthas


3 Answers

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() };
like image 123
MarcinJuraszek Avatar answered Oct 21 '22 22:10

MarcinJuraszek


Here is an easier way to do it for later Entity Framework versions.

var query = Data
.GroupBy(o => new { EventDate = o.EventDate.Date })
.Select(s => new SalesData()
{
    EventDate = s.Key.EventDate,
    Amount = s.Sum(o => o.Amount),
    Qty = s.Sum(o => o.Qty),
    RefundAmount = s.Sum(o => o.RefundAmount),
    RefundQty = s.Sum(o => o.RefundQty),
})
.OrderBy(o => o.EventDate)
.ToList();

return query;

like image 32
CTBrewski Avatar answered Oct 22 '22 00:10

CTBrewski


     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();
like image 2
Serdari Avatar answered Oct 22 '22 00:10

Serdari