我想搜索多个并获得结果。我发送此功能devicename
user
alarm
。填充这些变量时,它可以正常工作。但是当它们是空的时候,它不是。我只能填充devicename
变量。例如;
devicename = "test";
alarm="";
user="";
有时我可以填devicename
user
,有时我可以填devicename
alarm
..我无法从我的代码中获取任何数据。我需要帮助。这是我的代码:
List<ActivityLog> list = db.ActivityLog.Where(c => c.Devices.devName.ToLower().Contains(devicename.ToLower()))
.Where(c => c.Users.uName.ToLower().Contains(user.ToLower()))
.Where(c => c.AlarmCodes.aName.ToLower().Contains(alarm.ToLower()))
.OrderBy(c => c.dateTime).Skip(skip).Take(pageSize).ToList();
答案 0 :(得分:3)
我过去做过这个。
public IQueryable<ActivityLog> ApplyCriteria(Context db)
{
var activitySet = db.ActivityLog.AsQueryable();
if(!string.IsNullOrWhiteSpace(deviceName))
activitySet.Where(c => c.Devices.devName.ToLower().Contains(devicename.ToLower());
//and so on and so forth
return activitySet;
}
public Response SearchStuff(Criteria criteria)
{
using(var db = CreateContext())
{
var qry = criteria.ApplyApplyCriteria(db);
//In this instance, whatever is a list on my response object, but I believe it could be
//anything that handles IEnumerable
response.Whatever.AddRange(qry);
}
}
刚刚以这种方式构建了我的查询。然后在条件的调用者中我可以处理Queryable但是我想要。
答案 1 :(得分:3)
List<ActivityLog> list = db.ActivityLog.Where(c => devicename == "" || c.Devices.devName.ToLower().Contains(devicename.ToLower()))
.Where(c => user == "" || c.Users.uName.ToLower().Contains(user.ToLower()))
.Where(c => alarm == "" || c.AlarmCodes.aName.ToLower().Contains(alarm.ToLower()))
.OrderBy(c => c.dateTime).Skip(skip).Take(pageSize).ToList();
并且Mihai建议您可以将所有where语句组合在一起。
答案 2 :(得分:2)
你能把所有那些放在一个有OR条件的地方吗?像这样,它就像AND操作一样。
.ActivityLog.Where(c => c.Devices.devName.ToLower().Contains(devicename.ToLower()) ||
c.Users.uName.ToLower().Contains(user.ToLower()) ||
c.AlarmCodes.aName.ToLower().Contains(alarm.ToLower()))
.OrderBy(c => c.dateTime).Skip(skip).Take(pageSize).ToList();