我想知道是否有办法让这段代码更短:
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只是为了重复查询。 提前谢谢。
答案 0 :(得分: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
};