SQL server where子句等于而不是IN

时间:2017-04-14 12:10:32

标签: c# sql sql-server linq

以下是LINQ生成的T-SQL

SELECT 
    [Extent1].[ID] AS [ID], 
    [Extent1].[Name] AS [Name]
    FROM [dbo].[Hospital] AS [Extent1]
    WHERE ( EXISTS (SELECT 
        1 AS [C1]
        FROM ( SELECT 
            [Extent2].[ID] AS [ID]
            FROM [dbo].[HospitalDepartment] AS [Extent2]
            WHERE [Extent1].[ID] = [Extent2].[HospitalID]
        )  AS [Project1]
        WHERE  EXISTS (SELECT 
            1 AS [C1]
            FROM ( SELECT 
                [Extent3].[ID] AS [ID]
                FROM [dbo].[Unit] AS [Extent3]
                WHERE [Project1].[ID] = [Extent3].[HospitalDepartmentID]
            )  AS [Project2]
            WHERE  EXISTS (SELECT 
                1 AS [C1]
                FROM [dbo].[Device] AS [Extent4]
                WHERE ([Project2].[ID] = [Extent4].[UnitID]) AND ([Extent4].[DeviceTypeID] IN (10,20))
            )
        ) 

我需要在下面的代码中使用等于而不是IN,因为当我使用IN时,如果包含 10或20,则返回结果但是我想要的是如果等于 10和20

WHERE  EXISTS (SELECT 
            1 AS [C1]
            FROM [dbo].[Device] AS [Extent4]
            WHERE ([Project2].[ID] = [Extent4].[UnitID]) AND ([Extent4].[DeviceTypeID] IN (10,20))
        )

这里是Linq的源代码:

    var query = db.Hospitals.AsQueryable();


    if (DeviceTypeIDs != null)
    {

     IEnumerable<Guid> selectedDeviceTypeIDs = DeviceTypeIDs.Split(',').Select(Guid.Parse).AsEnumerable();
       query = query.Where(j => j.HospitalDepartments.Any(jj => jj.Units.Any(m => m.Devices.Any(w => selectedDeviceTypeIDs.Contains(w.DeviceTypeID)))));
    }

    if (UnitTypeID != null)
    {
        query = query.Where(j => j.HospitalDepartments.Any(www => www.Units.Any(u => u.UnitTypeID == UnitTypeID)));
    }

    if (DirectorateOfHealthID != null)
    {
        query = query.Where(h => h.DirectorateHealthID == DirectorateOfHealthID);
    }


    query = query.Where(j => j.HospitalDepartments.Any(u => u.Units.Any(d => d.Devices.Any(s => s.Status == Enums.DeviceStatus.Free)))
    && j.HospitalDepartments.Any(hd => hd.Units.Any(u => u.Beds.Any(b => b.Status == Enums.BedStatus.Free))));





    var list = query.ToList();

谢谢

1 个答案:

答案 0 :(得分:0)

替换

m => m.Devices.Any(w => selectedDeviceTypeIDs.Contains(w.DeviceTypeID))

m => m.Devices.All(w => selectedDeviceTypeIDs.Contains(w.DeviceTypeID)) && selectedDeviceTypeIDs.All(w => m.Devices.Any(d => d.DeviceTypeID = w))

您也可以像这样重构:

创建方法

private bool areEquivalent(List<int> a, List<int> b) { return (a.Count == b.Count) && !a.Except(b).Any(); }

然后

m => { var deviceTypes = m.Devices.Select(d => d.DeviceType).ToList(); return areEquivalent(selectedDeviceTypeIDs, deviceTypes);}