Question

I need to retrieve a collection of

public class TemperatureModel
{
    public string SensorType { get; set; }
    public double RoomTemperature { get; set; }
    public DateTime Created { get; set; }
}

for the latest room temperature for each temperature sensor represented in the database.

I have a Linq query that retrieves the latest room temperature written to the database for each temperature sensor.

var latestTemperatureQuery =
    from temperature in db.RoomTemperature
    join sensor in db.Sensor on temperature.SensorId equals sensor.Id
    group temperature by temperature.SensorId into groupedRoomTemperature
    select groupedRoomTemperature.OrderByDescending(t => t.Created)
    .FirstOrDefault();

I'm struggling to modify the query above to populate the TemperatureModel DTO/POCO class. I obviously have to perform a JOIN operation to get the appropriate SensorType from the applicable database table and then have to do something like

select new TemperatureModel
{
     SensorType = // Selected SensorType value.
     RoomTemperature = // Selected RoomTemperature value.
     Created = // Selected Created value.
}

while still only selecting the last temperature written to the database for each temperature sensor. Any ideas on how to modify this query to populate my DTO/POCO class?

Was it helpful?

Solution

Ok I found the solution, hope this helps someone in the future. I made use of the let keyword to keep track of the latest room temperatures that was written to the database. By doing this I could perform all my joins, select the results into my DTO/POCO class and then select only the latest by ordering by date and using .First(). I changed my linq query to

var latestTemperatureQuery =
    from temperature in db.RoomTemperature
    join sensor in db.Sensor on temperature.SensorId equals sensor.Id
    join sensorType in db.SensorType on sensor.TypeId equals sensorType.Id
    let temperatureModel = new TemperatureModel
    {
        SensorType = sensorType.Type,
        RoomTemperature = temperature.Temperature,
        Created = temperature.Created
    }
    group temperature by temperatureModel.SensorId into groupedTemperatureModel
    select groupedTemperatureModel.OrderByDescending(t => t.Created)
   .FirstOrDefault();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top