2016-02-04 69 views
0

我想實現這樣的空值: 如果有那麼一個匹配的ID根據它過濾後的結果,否則繞過條件如何在多處理很多關係

.Where(x => x.NeighbourhoodId == (id ?? x.NeighbourhoodId) 

,但我不得到了許多正確的語法一對多的關係:

public JsonResult GetPost(int? id, int? tagid) 
    { 
    var ret = from data in db.Posts.Include(x => x.Tags) 
       .Include(x => x.Neighbourhood) 
       .OrderByDescending(x => x.PostedDate) 
       .Where(x => x.NeighbourhoodId == (id ?? x.NeighbourhoodId) 
       && x.Tags.Any(t => t.TagId == tagid)) 
       .ToList() 
       select new 
        { 
         TagName = string.Join(",", data.Tags.Select(t => t.TagName)), 
         Message = data.Message, 
        // and other related stuff 
        } 

這裏,就像你看到的,這個where子句中包含多個條件,我想篩選post.There將是唯一一個值參數。意味着如果id參數有值,那麼tagid將爲null,如果tagid爲null,那麼id會有一些值。

現在,我想如果tagid中有空值,那麼這個查詢仍然應該運行。現在,它沒有在數據庫中工作becoz,沒有空的tagid或null的帖子,如何做到這一點。有什麼建議麼??

+0

過濾請重新表述的問題。 'id'爲'null'時會發生什麼?當'tagId'爲'null'?繞過相應的條件? –

+0

@IvanStoev我已經編輯了這個問題在末端PLZ看看 – duke

回答

1

如果我理解正確的話,你需要建立動態的基礎上傳遞的參數是這樣

var posts = db.Posts 
    .Include(x => x.Tags) 
    .Include(x => x.Neighbourhood) 
    .OrderByDescending(x => x.PostedDate); 
if (id != null) 
    posts = posts.Where(x => x.NeighbourhoodId == id.Value); 
if (tagid != null) 
    posts = posts.Where(x => x.Tags.Any(t => t.TagId == tagid.Value)); 
var ret = from data in posts 
    // ... the rest 
+0

好吧,它會工作我以前嘗試過它,但我正在尋找任何解決方案與空合併運營商btw upvote從我thnk u – duke

+1

@duke null合併和其他「嵌入式」參數檢查技巧會生成非常差的SQL查詢。我建議您在任何時候使用上述方法進行動態過濾 - 它「僅花費」幾行代碼,但會產生最佳的更快查詢。 –

+0

爲響應,我試圖使用空合併運算符的主要原因becoz我認爲這是很快,如果你說如果使用if語句會導致更快的最佳查詢,那麼我肯定會使用它們@Ivan Stoev – duke