如何创建一个动态where子句
本文关键字:一个 动态 where 子句 创建 何创建 | 更新日期: 2023-09-27 18:15:36
下面的代码
string cluase = string.Empty;
string whereValue = string.Empty;
foreach (var i in whereCluaseItems)
{
if (cluase != "")
{
cluase += " and " + i.Name;
}
else
{
cluase = i.Name;
}
if (whereValue != "")
{
whereValue += "," + i.Value;
}
else
{
whereValue = i.Value;
}
}
var result = context.vCatalogItemsDetails
.Where(cluase, whereValue)
// since where syntax has to be like this : where("@landuageID=@0,categoryid=@1", 1,1)
.OrderBy("itemID")
.Skip((pageN - 1) * 10).Take(10);
子句是一个字符串,它包含"languageId=@0, categoryid=@1"
whereValue也是一个字符串,它包含"1,1"
我需要去掉那些引号。我该怎么做呢?
对于这种"动态" where子句,通常不需要使用基于表达式的特征。您只需要意识到可以组成多个Where
调用。
public static IEnumerable<Person> Filter(this IEnumerable<Person> source,
string firstname, string lastname)
{
if (firstname != null)
{
source = from person in source
where person.Firstname.Contains(firstname)
select person;
}
if (lastname != null)
{
source = from person in source
where person.Lastname.Contains(lastname)
select person;
}
return source;
}
同样的技术也适用于IQueryable<T>
在动态LINQ库的帮助下可以做到这一点,它就像这样简单:
var result = context.vCatalogItemsDetails
.Where(cluase, whereValue)
.Where("landuageID=1 AND categoryid=1")
.OrderBy("itemID")
.Skip((pageN - 1) * 10).Take(10);