我正在尝试创建一个动态where子句,然后将其嵌入到LINQ
查询中,但我不知道该怎么做。
StringBuilder whereClause = new StringBuilder();
if (groupId>=0)
{
whereClause.Append("type.GroupID == groupId");
}
if (siteId>=0)
{
if (whereClause.Equals("type.GroupID == groupId"))
{
whereClause.Append("&&");
}
whereClause.Append("type.SiteID == siteId");
}
if (string.IsNullOrEmpty(typeName))
{
if (whereClause.Equals("type.GroupID == groupId&&type.SiteID == siteId"))
{
whereClause.Append("&&");
}
whereClause.Append("type.ThermometerTypeName == typeName");
}
var thermoTypes = execore from type in db.TempR_ThermometerType
where whereClause
select type).ToList();
答案 0 :(得分:8)
你正在解决LINQ存在的全部原因!
请改为尝试:
var query = from type in db.TempR_ThermometerType
select type;
if (groupId >= 0)
{
query = query.Where(type => type.GroupID == groupId);
}
if (siteId >= 0)
{
query = query.Where(type => type.SiteID == siteId);
}
...
return query.ToList();
答案 1 :(得分:0)
如果您需要简单的and
逻辑,只需使用多个Where
子句:
var query = db.TempR_ThermometerType.AsQueryable();
if(..)
{
query.Where(...);
}
if(..)
{
query.Where(...);
}
....
使用PredicateBuilder
或Expressoin
PredicateBuilder
示例:
IQueryable<Product> SearchProducts (params string[] keywords)
{
var predicate = PredicateBuilder.False<Product>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or (p => p.Description.Contains (temp));
}
return dataContext.Products.Where (predicate);
}
答案 2 :(得分:0)
或者你可以使用布尔逻辑(以及多个where
语句暗示结合的事实 - 它们之间有AND
)并写一个查询:
from type in db.TempR_ThermometerType
where groupId < 0 || type.GroupId == groupId
where siteId < 0 || type.SiteId == siteId
where typename == "" || type.TheromometerTypeName == typeName
select type;
查询更大,但代码非常简洁,数据库服务器只需要缓存一个参数化查询执行计划而不是几个。