LINQ-检查空值,然后将语句追加回查询



我正在使用Linq进行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条件中包装的查询的第二部分附加到原始查询?

你可以试试这个:

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();

相关内容

  • 没有找到相关文章

最新更新