I am trying to make a dynamic where clause and then embed it in the to LINQ
query but i don't know how to do it.
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();
You're going around the whole reason LINQ exists!
Try this instead:
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();
if you need simple and
logic just use multiple Where
clauses:
var query = db.TempR_ThermometerType.AsQueryable();
if(..)
{
query.Where(...);
}
if(..)
{
query.Where(...);
}
....
to generate your dynamic clauses use PredicateBuilder
or via Expressoin
's
PredicateBuilder
example from link:
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);
}
Or you can use boolean logic (and the fact that multiple where
statements imply conjunction - have AND
between them) and write one query:
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;
The query is bigger, but the code is quite concise and the DB server would only have to cache one parametrized query execution plan instead of several.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.