I have a table called 'Samples' with the following columns: Id, Type, Quantity, Unit, SampleTime.
I have the following statement that calculates the daily weight average:
weightchart.data = db.Samples
.Where(n => n.Type == "weight")
.GroupBy(n => DbFunctions.TruncateTime(n.SampleTime))
.Select(item => new ChartData()
{
timestamp = item.Key,
average = item.Average(a => a.Quantity),
max = item.Max(a => a.Quantity),
min = item.Min(a => a.Quantity),
count = item.Count()
}).OrderBy(n => n.timestamp).ToList();
charts.Add(weightchart);
Now I would like to get the hourly average. I can't figure out how to do this. I'm new to c#, linq and entities.
Update: I've updated my statement to this:
weightchart.data = db.Samples.Where(n => n.Type == "weight").GroupBy(n => new { Date = n.SampleTime.Date, Hour = n.SampleTime.Hour }).Select(item => new ChartData()
{
timestamp = new DateTime(item.Key.Date.Year, item.Key.Date.Month, item.Key.Date.Day, item.Key.Date.Hour, 0, 0),
average = item.Average(a => a.Quantity),
max = item.Max(a => a.Quantity),
min = item.Min(a => a.Quantity),
count = item.Count()
}).OrderBy(n => n.timestamp).ToList();
charts.Add(weightchart);
However I get this exception:
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code Additional information: The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.