我想知道是否有一种方法,我可以让这个块码短: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