2016-07-14 39 views
-2

我有一個博客帖子三個表:如何過濾在實體框架與多個選擇框結果

  • post_tablepost_id,POST_TITLE崗位性質等
  • category_table包括兩列如category_id的和類別名稱
  • post_category_table這是用於post_tablecategory_table之間的關係的接口表,並且它具有兩個外鍵列,例如post_idcategory_id

請注意,每個帖子可以有一個或多個類別。

multiple select box (image)

現在我有類別的用戶能夠選擇一個或多個類別的多個選擇框(如附接的圖像)。當用戶從選擇框中選擇一個或多個類別時,結果應限於所選類別。

如何使用實體框架爲此問題編寫「Where」條件?

我的代碼是:

var query = context.post_Table 
    .Select(postinfo => new { 
     post_title = postinfo.post_title, 
     post_date = postinfo.post_date, 
     post_id=postinfo.post_id,   
     post_category = postinfo.post_category_table.Select(cc => new { 
      cc0=cc.category_id, 
      cc1 = cc.category_table.category_name, 
     }), 

    }).Where(???) 

回答

0

你應該能夠得到從多選擇框類別ID的集合(所選類別的ID)。

我們稱之爲selectedCategoryIds,我們假設它是一個IEnumerable<int>

要根據所選類別,你可以這樣做篩選結果:

var query = context.post_Table 
    .Select(postinfo => new 
    { 
     post_title = postinfo.post_title, 
     post_date = postinfo.post_date, 
     post_id=postinfo.post_id,   
     post_category = postinfo.post_category_table.Select(cc => new 
     { 
      cc0 = cc.category_id, 
      cc1 = cc.category_table.category_name, 
     }) 
    }) 
    .Where(info => info.post_category.Any(c => selectedCategoryIds.Contains(c.cc0))); 

編輯

如果你有一些有條件的邏輯,你可以拆分並據此撰寫查詢:

var query = context.post_Table 
    .Select(postinfo => new 
    { 
     post_title = postinfo.post_title, 
     post_date = postinfo.post_date, 
     post_id=postinfo.post_id,   
     post_category = postinfo.post_category_table.Select(cc => new 
     { 
      cc0 = cc.category_id, 
      cc1 = cc.category_table.category_name, 
     }) 
    }); 

if(selectedCategoryIds != null && selectedCategoryIds.Any()) 
{ 
    query = query.Where(info => info.post_category.Any(c => selectedCategoryIds.Contains(c.cc0))); 
} 

但是,如果你的條件邏輯比上面的小例子更復雜,請看看在my answer to a previous question爲什麼你應該使用謂詞生成器。

+0

感謝您的回覆。但它爲'info.post_category.cc0'返回錯誤。 錯誤消息是: IEnumerable <<匿名類型:int cc0,字符串cc1 >>'不包含'cc0'的定義,也沒有擴展方法'cc0'接受類型爲'IEnumerable <<匿名類型:int cc0,字符串cc1 >>'可以找到(你是否缺少using指令或程序集引用?)' – msitworld

+0

@msitworld,對不起,我沒有注意到'post_category'是一個集合。我糾正了答案。 – RePierre

+0

非常感謝。有效。再次感謝。 :)) – msitworld