Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
EF Linq include last

I have 2 tables one with cities and another with temperature/date values for the cities, a city can have multiple dates with temperature.

how could I by EF + linq bring the cities + the most recent temperature of each one

something like: _context.city.include(x=> x.temperature().last());

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could achieve this by projecting the city and the last temperature to a new object, in a Select expression. The code snippet you included in your question is missing a few steps, so I'm going to take a guess at your data structures:

await _context.Cities.Select(city => new
{
    City = city,
    LastTemperature = city.Temperatures
                         .OrderByDescending(t => t.DateRecorded)
                         .FirstOrDefault(),
}).ToListAsync();
over 4 years ago · Santiago Trujillo Report

0

You always should take control over which temperature is "last" by ordering them by a chosen property. Doing that, it makes sense to use Take(1) in Include, for example to get the most recent one:

_context.Cities
    .Include(x=> x.Temperatures.OrderByDescending(t => t.Date).Take(1));

Filtered/ordered Include is supported as of EF core 5.

Since you're already trying something along these lines I'm assuming you're using EFC 5 or 6.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!