2016-09-30 46 views
2

我想知道是否有一種方法,我可以讓這個塊碼短:EF添加where子句中使用IF和切換條件

if (rdball.Checked ==true) 
{ 
    var query = from u in context.User 
    join ur in context.UserRole on u.ID equals r.UserID 
    join r in context.Role on ur.RoleID.ToString() equals r.ID.ToString() 
    select new 
    { 
    u.ID, 
    u.Nick, 
    u.LastLogin, 
    Role = ur == null ? String.Empty : r.Name 
    }; 
} 
else 
{ 
    var query = from u in context.User 
    join ur in context.UserRole on u.ID equals r.UserID 
    join r in context.Role on ur.RoleID.ToString() equals r.ID.ToString() 
    where sg.GroupID == Convert.ToInt32(cmbGroupSearch.SelectedValue) 
    select new 
    { 
    u.ID, 
    u.Nick, 
    u.LastLogin, 
    Role = ur == null ? String.Empty : r.Name 
    }; 
} 

沒有EF我通常使用默認的查詢字符串,並添加最後一部分與哪裏取決於如果radioubutton被檢查或不。像這樣

if (rdball.Checked ==true) 
    query = query + " where sg.GroupID ==" + Convert.ToInt32(cmbGroupSearch.SelectedValue) 
end if 

但我不明白如何用EF做到這一點。我不喜歡2000行代碼變成3000只是爲了重複查詢。 在此先感謝。

+1

我想你可以做這樣的事情'那裏sg.GroupID == Convert.ToInt32(rdball.Checked sg.GroupID? cmbGroupSearch.SelectedValue)' –

+0

你可以分開查詢的where部分。看到這個[答案](http://stackoverflow.com/a/11335767/2030565)。 – Jasen

回答

1

Where採取任何布爾表達式,所以你可以做這樣的事情:

var query = from u in context.User 
    join ur in context.UserRole on u.ID equals r.UserID 
    join r in context.Role on ur.RoleID.ToString() equals r.ID.ToString() 
    where rdball.Checked ? sg.GroupID == Convert.ToInt32(cmbGroupSearch.SelectedValue) : true 
    select new 
    { 
     u.ID, 
     u.Nick, 
     u.LastLogin, 
     Role = ur == null ? String.Empty : r.Name 
    }; 
+0

正是我在找的東西。謝謝 – bondagemaster

+0

看EF如何轉換這個查詢可能很有趣。 – bubi

+0

@bubi你可能會嘗試使用你的上下文的Database.Log對象或嘗試調用query.ToTraceString(),看看更多[here](http://stackoverflow.com/questions/1412863/how-do-i -view最SQL生成由這實體框架)。 – Gasper