2017-08-28 40 views
0

我正在運行一個查詢,該查詢將根據位置搜索和日期獲取結果。我有一個geography列的位置點(緯度/經度)索引。當我搜索某個日期的事件時,它將搜索該日期內距離(半徑)內的所有事件。從實體框架中的查詢獲取多個不同的值

問題是,如果有10個事件,所有在同一天的同一位置,所有10個結果將返回到第一頁。我想將它們混合起來,並且只顯示每個位置的2-3,以使結果集有所變化,因此用戶不會只看到一個位置的所有事件。

我知道我可以使用不同的只從每個位置獲取一個事件,但我將如何使用它來獲得2-3個不同的值?

這是我的查詢到目前爲止。

viewModel.Events = dbContext.YogaSpaceEvents 
          .Where(i => i.EventDateTime >= adjustedSearchDate && 
             i.LocationPoints.Distance(location) <= radius) 
          .Distinct() 
          .OrderBy(i => i.EventDateTime) 
          .Select(i => new EventResult 
              { 
               //fill view model here 
              }) 
          .ToPagedList(Page, 10); 

回答

0

我不認爲有一種方式來獲得EF產生這樣的查詢,這對於SQL Server的將是這樣的:

with q as 
(
    select *, 
     (row_number() over (partition by StateProvinceId order by CityID) -1)/3 MyRanking 
    from Application.Cities 
) 
select CityId, CityName,StateProvinceID 
from q 
order by MyRanking, StateProvinceID, CityID 
offset 10 rows 
fetch next 20 rows only 

注意這個例子不使用距離。但是這個想法是相同的:每個州的前三個城市先返回,然後是下一個3等。

或者您可以獲取所有匹配事件並在內存中對其進行排序。

0

我想你應該能夠做這樣的事情:

dbContext.YogaSpaceEvents 
.Where(i => i.EventDateTime >= adjustedSearchDate && 
      i.LocationPoints.Distance(location) <= radius) 
.GroupBy(i => i.Geography) 
.SelectMany(g => g.OrderBy(x => x.EventDateTime).Take(3)) 
.Select(i => new EventResult { //fill view model here }) 
.ToPagedList(Page, 10);