将动态WHERE子句组装到LINQ语句的最佳方法是什么?
我在表单上有几十个复选框,并将它们传递回:Dictionary <string,List <string >>(Dictionary <fieldName,List <values >>)到我的LINQ查询.
public IOrderedQueryable<ProductDetail> GetProductList(string productGroupName, string productTypeName, Dictionary<string,List<string>> filterDictionary)
{
var q = from c in db.ProductDetail
where c.ProductGroupName == productGroupName && c.ProductTypeName == productTypeName
// insert dynamic filter here
orderby c.ProductTypeName
select c;
return q;
}
Run Code Online (Sandbox Code Playgroud) 假设我们需要应用几个条件来从一个名为"Things"的表中进行选择(未知计数和性质)
如果条件已知,我们可以写
db.Things.Where(t=>foo1 && foo2 || foo3);
Run Code Online (Sandbox Code Playgroud)
但是如果我们必须以编程方式构建Where条件,我可以想象我们如何应用ANDed条件
IQuerable DesiredThings = db.Things.AsQuerable();
foreach (Condition c in AndedConditions)
DesiredThings = DesiredThings.Where(t => GenerateCondition(c,t));
Run Code Online (Sandbox Code Playgroud)
ORed条件怎么样?注意:我们不想执行union,unique或任何其他代价高昂的操作,我们希望生成一个查询,好像我们将它写成ad-hock
提前致谢.
PredicateBuilder:动态编写表达式谓词
我有一些C#代码使用nhibernate查询数据库,如下所示:
public void Query()
{
IEnumerable<Project> list = session.Query<Project>()
.Where(p => !p.IsDeleted)
.FetchMany(r => r.UnfilteredProjectApplications)
.ThenFetch(r => r.Application)
.ToList()
}
Run Code Online (Sandbox Code Playgroud)
我现在有许多用户驱动程序过滤器,因此,根据传入的参数,我想添加到where子句.所以像这样:
public void Query(string name)
{
if (!String.IsNullOrEmpty(name)
{
IEnumerable<Project> list = session.Query<Project>()
.Where(p => !p.IsDeleted && p.Name == name)
.FetchMany(r => r.UnfilteredProjectApplications)
.ThenFetch(r => r.Application)
.ToList()
}
}
else
{
IEnumerable<Project> list = session.Query<Project>()
.Where(p => !p.IsDeleted)
.FetchMany(r => r.UnfilteredProjectApplications)
.ThenFetch(r => r.Application)
.ToList()
}
Run Code Online (Sandbox Code Playgroud)
用户可以选择一个或多个过滤器.可以想象,鉴于大量的组合,上面的代码会变得非常复杂.有没有一种优雅的方法可以在这里添加一个带有附加逻辑块的where子句.有些可能很简单,比如
p.Name == name
Run Code Online (Sandbox Code Playgroud)
但其他人可能更复杂,如:
p.ProjectApplications.Select(r => r.Application).Any(s => applicationIds.Contains(s.Id)))
Run Code Online (Sandbox Code Playgroud)
正如我所说,可能有零个或多个不同的过滤器..
我在其他情况下看到,人们建议建立where子句
query …Run Code Online (Sandbox Code Playgroud) c# ×3
where-clause ×2
.net ×1
dynamic ×1
filter ×1
lambda ×1
linq ×1
linq-to-sql ×1
nhibernate ×1