Linq哪里有可能出现空引用的条件

时间:2016-08-26 21:41:43

标签: c# entity-framework linq linq-to-entities where-clause

所以我正致力于使用Entity Framework转换SQL Server存储过程。我要做的一个查询涉及一个左连接,其中一个表最终在where子句中使用。 (PS-忽略当前选择,我为了调试目的而改变它)

    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);
每当从where子句中删除union3时,

o都会生成一组sr。如何在查询中包含该表,其效果与以下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是一个用于进一步存储过程的表,它正常工作

1 个答案:

答案 0 :(得分:0)

您可以尝试如下所示。

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

您可以在此处了解Perform Left Outer Joins