C# Linq Where可能存在空引用的条件
因此,我正在使用实体框架转换SQL Server存储过程。我必须做的一个查询涉及到一个表的左连接,该表最终被用在where子句中。PS忽略当前的select,我为了调试目的更改了它C# Linq Where可能存在空引用的条件,c#,entity-framework,linq,linq-to-entities,where-clause,C#,Entity Framework,Linq,Linq To Entities,Where Clause,因此,我正在使用实体框架转换SQL Server存储过程。我必须做的一个查询涉及到一个表的左连接,该表最终被用在where子句中。PS忽略当前的select,我为了调试目的更改了它 var union3 = (from o in orgs from uos in accessOrgIds.Where(x => o.Id == x) from sr in secRoles.Where(x => x.Id =
var union3 = (from o in orgs
from uos in accessOrgIds.Where(x => o.Id == x)
from sr in secRoles.Where(x => x.Id == secRoleId).DefaultIfEmpty()
where (o.StatusId == 1)
&& (secRoleId == 0 || sr == null ? false : sr.Id == secRoleId)
select o);
每当sr从where子句中删除时,union3就会产生一个o集。如何在查询中包含该表,并具有与以下SQL相同的效果
SELECT
ISNULL(SR.Id, @securityRoleId),
O.Id,
O.Name AS OrganizationName,
SR.Name AS SecurityRoleName,
-1 AS IsSelected,
SR.[Description],
SR.IsSystem,
SR.IsOATI,
ISNULL(SR.StatusId, 1) AS StatusId,
SR.IsAdmin
FROM
Organizations O WITH (NOLOCK)
INNER JOIN @userOrganizations UOS ON UOS.OrganizationId = O.Id
LEFT JOIN SecurityRoles SR WITH (NOLOCK) ON SR.Id = @securityRoleId
WHERE O.StatusId = 1
AND (@securityRoleId = 0 OR SR.Id = @securityRoleId)
PS-@userOrganizations是存储过程的一个更高级的表,它工作正常您可以按如下所示进行尝试
var union3 = (from o in orgs
join uos in userOrganizations on uos.OrganizationId equals o.Id
join sr in SecurityRoles on o.secRoleId equals sr.Id into gj
from subsr in gj.DefaultIfEmpty()
where (o.StatusId == 1)
&& (o.secRoleId == 0 || sr.Id == o.secRoleId)
select o);
在这里您可以了解。您可以按如下所示进行尝试
var union3 = (from o in orgs
join uos in userOrganizations on uos.OrganizationId equals o.Id
join sr in SecurityRoles on o.secRoleId equals sr.Id into gj
from subsr in gj.DefaultIfEmpty()
where (o.StatusId == 1)
&& (o.secRoleId == 0 || sr.Id == o.secRoleId)
select o);
在这里,你可以找到关于这个问题的答案