LINQ - 必填字段和可为空的字段不做要求

4
我正在为一个asp.net应用程序构建搜索功能,并使用LINQ to SQL根据所选的搜索条件检索数据。搜索条件包括:
1. 国家 2. 城市 3. 区域 4. 房间数量 5. 租赁周期
只有第一个搜索条件国家是必填字段。但是,如果用户输入了条件2、3、4和/或5的值,则应考虑这些输入值,并仅检索与所有输入搜索条件匹配的结果。请注意,如果条件2、3、4和/或5中的任何一个为空(null),则LINQ应该作为“不关心”并返回该行。
例如,如果输入的条件如下:
1. 国家=美国 2. 城市=null 3. 区域=null 4. 房间数量=null 5. 租赁周期=null
那么应该返回所有Country==USA的行。
另一个例子:
1. 国家=英国 2. 城市=null 3. 区域=null 4. 房间数量=5 5. 租赁周期=null
然后应返回所有Country==UK且NumberOfRooms==5的行。
如何在LINQ to SQL中实现这一点?
以下是我目前的代码:
var data = from x in db.Units where x.Country == coutnryID && /*PLEASE HELP!*/ select x;
3个回答

4
尝试这个(假设您想搜索的变量是cityIddistrictIdroomsrentCycle):
var data = from x in db.Units
    where x.Country == countryId
        && (cityId == null || x.City == cityId)
        && (districtId == null || x.District == districtId)
        && (rooms == null || x.Rooms == rooms)
        && (rentCycle == null || x.RentCycle == rentCycle)
    select x; 

我的意思是,如果您要搜索的变量为null,则忽略它们,否则将它们与Unit中相应的字段匹配。


如果我需要从多个表中获取记录以实现相同的功能,那么我该如何实现呢?谢谢。 - Zaker
1
@用户,只需使用外连接即可。 - Mathew Thompson
请给一个例子。 - Zaker

1

您可以分阶段构建查询:

var query = from x in db.Units  where x.Country == countryId;
if (cityId != null)        query = query.Where(x.City == cityId);
if (districtId != null)    query = query.Where(x.City == districtId);
if (rooms != null)         query = query.Where(x.Rooms == rooms);
if (rentCycle != null)     query = query.Where(x.RentCycle == rentCycle);
var data = query.Select();

这会给你稍微更高效的SQL,但C#代码会变得稍微凌乱一些。


1

使用 GetValueOrDefault,如果为 null,则提供默认值给当前值:

var data = from x in db.Units
    where x.Country == countryId
        && (x.City == cityId.GetValueOrDefault(x.City))
        && (x.District == districtId.GetValueOrDefault(x.District))
        && (x.Rooms == rooms.GetValueOrDefault(x.Rooms))
        && (x.RentCycle == rentCycle.GetValueOrDefault(x.RentCycle))
    select x; 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接