LINQ:如何在查询中使用Equals

时间:2017-04-14 17:46:34

标签: c# sql-server entity-framework linq

我需要使用Equals方法或类似的方法而不是使用Contains方法,因为我想在数据库中搜索selectedDeviceTypeIDs数组中的确切值而不是任何一个。

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

这是我的完整代码:

 public HttpResponseMessage GetAvailableHospitalsByAjax(System.Guid? DirectorateOfHealthID = null, System.Guid? UnitTypeID = null, string DeviceTypeIDs = null)
    {

        Context db = new Context();
        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();
        return Request.CreateResponse(HttpStatusCode.OK, list);
    }

1 个答案:

答案 0 :(得分:0)

如果IN中的foofoo.Contains( ),则EF6支持SQL IList<T>运算符,例如,此Linq:

Int32[] desired = new Int32[] { 1, 2, 3, 4 };

IQueryable<Item> itemsQuery = db.Items.Where( item => desired.Contains( item.SomeValue ) );

...将转换为:

SELECT Item.* FROM Items WHERE SomeValue IN ( 1, 2, 3, 4 )

我不完全确定具体细节,但我认为如果您将selectedDeviceTypeIDsIQueryable<Guid>转换为Guid[](或至少IList<Guid>),那么EF还会为您生成IN查询。