[英]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.表一包含一个区域列表,表二包含一个样本列表,每个样本行都包含
Area_ID
作为外键。
I need to retrieve all the records in my Area table with only the most recent corresponding Sample Status.我需要检索我的 Area 表中的所有记录,并且只使用最新的相应样本状态。 I have this query, but it just returns one Area with the most recent sample from the Sample table:
我有这个查询,但它只返回一个带有 Sample 表中最新样本的区域:
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
:一个解决方案可能是过滤你的第二个
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
:假设您在
Area
和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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.