我有一个查询两个表的LINQ查询,并成功返回记录。我希望它只返回最近的记录,但我无法让它工作。它返回所有记录而没有错误。
我的查询是:
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);
完全卡住了,非常感谢!
答案 0 :(得分:3)
你在错误的地方调用Take()
方法,你必须写一些类似的东西:
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();
如果您想要返回集合,那么您可以使用Take(1)
而不是FirstOrDefault()
,因为它不会返回集合。
答案 1 :(得分:1)
我认为你想要实现的是:
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();
调用FirstOrDefault方法,您将获得最新记录,因为它将TOP(1)添加到您的Linq查询生成的SQL查询中。