简体   繁体   中英

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();

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
                    };

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