2011-06-17 79 views
6

我有一個模型,其中一個地方有一些描述,這些描述與興趣(place.description.interests)相關聯。用戶查看地點的視圖在模型中以用戶身份表示,他們也有許多興趣。LINQ中找到重疊興趣

我想要做的排序是重疊的利益(包括零重疊),那裏有我當前的LINQ是描述:

place dest = (from p in _db.places 
          where p.short_name == id 
          select p).Single(); 

return View(dest); 

現在,下面將做什麼,我想在SQL上有問題的模式:

SELECT COUNT(interest_user.user_id) AS matches, description.* 
FROM description JOIN interest_description ON description.user_id = interest_description.user_id AND description.place_id = interest_description.place_id 
    JOIN interest ON interest_description.interest_id = interest.interest_id 
    LEFT JOIN interest_user ON interest.interest_id = interest_user.interest_id 
WHERE interest_user.user_id = 2 
    AND description.place_id = 1 
GROUP BY interest_description.user_id, interest_description.place_id 
ORDER BY matches DESC 

但我太新的Linq知道我將如何正確處理這個問題。理想情況下,我可以在傳遞強類型模型的同時將其取消。

到目前爲止,我已經成功的:

var desc = from d in _db.descriptions 
         from i in d.interests 
         from u in i.users.DefaultIfEmpty() 
         where d.place_id == PlaceID 
          && (u.user_id == userID 

(PlaceID和用戶名是傳遞給管理該控制器參數)。

簡而言之,考慮到這個linq,我只需要返回d,按i計數。

我的模型 enter image description here

+0

你能舉出輸入數據的例子嗎?應該給他們什麼結果? – 2011-06-17 06:21:23

+0

好吧,我有一個ID爲1的地方,ID爲1的用戶。我的用戶有興趣1,2,4。這個地方有1,2,3個描述,其中描述1有興趣1,2,描述2有興趣2,3,描述3有興趣1,2,3,4。當用戶1查看地點1時,說明應按3,1,2排序,因爲3有三個重疊的興趣,1有兩個重疊的興趣,2有一個重疊的興趣。 – 2011-06-17 16:03:08

回答

3

當你的linq查詢變得過於複雜時,我會建議你在你的數據庫中創建視圖,並將它們放在dbml設計器上。在linq查詢中進行大量分組導致低效的sql時,我遇到過幾種情況。使用視圖不僅會產生直接的linq查詢,還會使用你想要的sql。

3
place current_place = 
    _db.places 
    .Include("descriptions.interests.users") 
    .Where(p => p.place_id == place_id) 
    .First(); 

var interesting_descriptions = 
    from description1 in current_place.descriptions 
    select new { 
     description = description1, 
     matches = (
      from interest1 in description1.interests 
      from user1 in interest1.users 
      where user1.user_id = user_id 
      select 1 
     ).Count() 
    } into result 
    orderby result.matches descending 
    select result; 

這大致相當於SQL

SELECT 
    description.*, 
    (
     SELECT COUNT(*) 
     FROM interest_description 
     INNER JOIN interest_user 
      ON interest_user.interest_id = interest_description.interest_id 
     WHERE interest_description.place_id = description.place_id 
     AND interest_description.user_id = description.user_id 
     AND interest_user.user_id = @user_id 
    ) AS matches 
FROM description 
WHERE place_id = @place_id 
ORDER BY matches DESC 

對於給定的位置相關聯的每個描述,它計算的次數給定用戶發生對任何相關利益。

對於與用戶沒有共同興趣的描述,它將給出matches = 0。

由於GROUP BY/group ... by ... into很難處理帶條件的空集,所以需要使用內部查詢。

+0

我已更新我的示例SQL以準確顯示我正在嘗試執行的操作,恐怕我無法將您的示例翻譯成該示例。請注意,最後,我想要一個描述列表,根據它們與用戶有多少重疊的興趣來排序,對匹配本身不感興趣,以便我可以將結果傳遞給強類型化爲描述的視圖實體。 – 2011-06-20 03:36:28

+0

大家好,最後不僅僅是使用視圖,而是使用我上面發佈的查詢並返回描述的存儲過程更有效。*,允許我通過函數導入將SP映射到描述實體,並得到我所需要的。非常感謝幫助! – 2011-06-21 03:42:46