我想知道是否有一種方法,我可以讓這個塊碼短: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只是爲了重複查詢。 在此先感謝。
我想你可以做這樣的事情'那裏sg.GroupID == Convert.ToInt32(rdball.Checked sg.GroupID? cmbGroupSearch.SelectedValue)' –
你可以分開查詢的where部分。看到這個[答案](http://stackoverflow.com/a/11335767/2030565)。 – Jasen