【问题标题】:Linq Where condition where there's possibility of a null referenceLinq Where 条件可能存在空引用
【发布时间】:2016-08-26 21:41:42
【问题描述】:

所以我正在使用实体框架转换 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 子句中删除 sr 时,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 是一个在存储过程中进一步使用的表,它工作正常

【问题讨论】:

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


    【解决方案1】:

    你可以试试如下图。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      相关资源
      最近更新 更多