2016-03-24 39 views
1

我有一個查詢兩個表的LINQ查詢,併成功返回記錄。我希望它只返回最近的記錄,但我無法使其正常工作。它會返回所有記錄而不會出錯。使用內連接在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); 

完全卡住,幫助非常感謝!

回答

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(),因爲它不會返回集合。

+0

這很好,歡呼! – emerfan

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查詢查詢。