使用Linq-to-SQL并编写了以下查询,但我需要能够检查变量“UserRole.RoleID”是否为空。
var MemberQuery = from SystemUser in SecurityFilter.FilteredMembers(SecurityInfo, Context, DetailLevelEnum.NameOnly)
join Member in Context.webpages_Memberships on SystemUser.ID equals Member.UserId
join UserRole in Context.webpages_UsersInRoles on Member.UserId equals UserRole.UserId
where Member.IsConfirmed || IncludeUnconfirmed && Filter.SelectedMemberRoles.Contains(UserRole.RoleId) // This will sometimes be null
select SystemUser;
我已经考虑了许多方法,例如在if / else语句中包装查询或创建匿名类型。我不确定最好的方法是什么,但我想尝试做这样的事情:
var MemberQuery = from SystemUser in SecurityFilter.FilteredMembers(SecurityInfo, Context, DetailLevelEnum.NameOnly)
join Member in Context.webpages_Memberships on SystemUser.ID equals Member.UserId
where Member.IsConfirmed || IncludeUnconfirmed
select SystemUser;
if (Filter.SelectedMemberRoles != null)
{
MemberQuery = MemberQuery.Where( // Somthing here
join UserRole in Context.webpages_UsersInRoles on Member.UserId equals UserRole.UserId
where Filter.SelectedMemberRoles.Contains(UserRole.RoleId)
select /* Somthing */).Any();
}
如何将if条件中包含的查询的第二部分附加到原始查询?
答案 0 :(得分:0)
你可以试试这个:
var MemberQuery = (from SystemUser
in SecurityFilter.FilteredMembers(SecurityInfo, Context, DetailLevelEnum.NameOnly)
join Member in Context.webpages_Memberships on SystemUser.ID
equals Member.UserId
join _UserRole in Context.webpages_UsersInRoles on Member.UserId
equals _UserRole.UserId into _UserRole
from UserRole in _UserRole.DefaultIfEmpty()
where (Member.IsConfirmed || IncludeUnconfirmed )
&& (
Filter.SelectedMemberRoles == null || UserRole != null
&& Filter.SelectedMemberRoles.Contains(UserRole.RoleId)
)
select SystemUser)
.Distinct();