简体   繁体   中英

Select the most recent date in a LINQ query with an inner join

I have a LINQ query that queries two tables, and returns records successfully. I want it to only return the most recent record, but I'm having trouble getting it to work. It returns all of the records without an error.

My query is:

  var viewModel = from area in db.area
                  join sample in db.sample on area.location_id equals sample.location_id
                  from s in db.sample.OrderByDescending(s => s.sample_date).Take(1)

                  select new AreaViewModel { h_area = area, s_sample = sample };

                  return View(viewModel);

Totally stuck, help greatly appreciated!

You are calling Take() method at wrong place, you have to write something like:

var viewModel = (from area in db.area
                 join sample in db.sample on area.location_id equals sample.location_id
                 from s in db.sample
                 select new AreaViewModel 
                       { 
                         h_area = area, 
                         s_sample = sample 
                       }).OrderByDescending(s => s.s_sample.sample_date)
                         .FirstOrDefault();

if you want to return collection, then you can use Take(1) there instead of FirstOrDefault() , as it will not return collection.

I think what you are trying to achieve is this:

var area= (from area in db.area
           join sample in db.sample on area.location_id equals sample.location_id
           orderby sample.sample_date descending
           select new AreaViewModel { h_area = area, s_sample = sample }).FirstOrDefault();

Calling FirstOrDefault method you will get the most recent record due to it adds TOP(1) to the SQL query that is generated by your Linq query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM