Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query To Join Two Tables and Select Most Recent Records from Table B corresponding to Table A

I have two tables. Table One contains a list of Areas, and Table Two contains a list of Samples, with each Sample row containing Area_ID as a Foreign Key.

I need to retrieve all the records in my Area table with only the most recent corresponding Sample Status. I have this query, but it just returns one Area with the most recent sample from the Sample table:

var result = (
    from a in db.area
    join c in db.sample
    on a.location_id equals c.location_id

    select new 
    {
        name = a.location_name,
        status = c.sample_status,
        date = c.sample_date
    }).OrderByDescending(c => c.date).FirstOrDefault();

1 Answers

A solution could be filtering your second DbSet:

 var result =  from a in db.area
               join c in db.sample.Where(s=>s.location_id==a.location_id).OrderByDescending(c => c.sample_date).Take(1)
               on a.location_id equals c.location_id 
               select new 
                    {
                         name = a.location_name,
                         status = c.sample_status,
                         date = c.sample_date
                    };

Another solution could be applying a group join:

 var result =  from a in db.area
               join c in db.sample
               on a.location_id equals c.location_id into samples
               let sample=samples.OrderByDescending(c => c.sample_date).FirstOrDefault()
               select new 
                    {
                          name = a.location_name,
                          status = sample.sample_status,
                          date = sample.sample_date
                    };

If you use navigation properties could be even easier. Supposing you have a one to many relationship between Area and Sample:

var result =from a in db.area
            let sample= a.Samples.OrderByDescending(c => c.sample_date).FirstOrDefault()
            select new 
                    {
                          name = a.location_name,
                          status = sample.sample_status,
                          date = sample.sample_date
                    };
like image 106
octavioccl Avatar answered Sep 10 '25 02:09

octavioccl