添加IF和switch条件的where子句
本文关键字:where 子句 条件 switch IF 添加 | 更新日期: 2023-09-27 18:09:46
我想知道是否有一种方法可以使这个块代码更短:
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,我通常使用默认查询创建字符串,并根据是否选中了单选按钮添加带有where的最后一部分。这样的if (rdball.Checked ==true)
query = query + " where sg.GroupID ==" + Convert.ToInt32(cmbGroupSearch.SelectedValue)
end if
但我不明白如何做到这一点与EF。我不希望2000行代码变成3000行只是为了重复查询。
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
};