简体   繁体   English

LINQ to SQL-PredicateBuilder

[英]LINQ to SQL - PredicateBuilder

Quick question on how to get even more out of PredicateBuilder. 关于如何从PredicateBuilder中获得更多收益的快速问题。 It works as per below: 它按以下方式工作:

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);
}

The question is, what if I would like to search by an arbitrary member as well, ie pass the function string[] as the keywords, but also the field to search by, eg fieldToSearch, and replace the p=> p.Description.Contains(temp)); 问题是,如果我也想按任意成员进行搜索,即将函数string []作为关键字传递,还要传递要搜索的字段(例如fieldToSearch)并替换p => p.Description,该怎么办?包含(temp)); with something allowing searching by fieldToSearch? 允许通过fieldToSearch搜索的内容?

Is this possible, is it a bad idea? 这可能吗,这是一个坏主意吗?

For what you want to do, Dynamic Linq might be more appropriate. 对于您想做的事情, 动态Linq可能更合适。

While writing type-safe queries is great for most scenarios, there are cases where you want the flexibility to dynamically construct queries on the fly. 尽管编写类型安全查询在大多数情况下非常有用,但在某些情况下,您需要灵活地动态地动态构建查询。 For example: you might want to provide business intelligence UI within your application that allows an end-user business analyst to use drop-downs to build and express their own custom queries/views on top of data. 例如:您可能希望在应用程序中提供商业智能UI,以允许最终用户业务分析师使用下拉菜单来构建和表达自己的自定义查询/视图(基于数据)。

Traditionally these types of dynamic query scenarios are often handled by concatenating strings together to construct dynamic SQL queries. 传统上,通常通过将字符串连接在一起以构造动态SQL查询来处理这些类型的动态查询方案。 Recently a few people have sent me mail asking how to handle these types of scenarios using LINQ. 最近,一些人给我发送了邮件,询问如何使用LINQ处理这些类型的场景。 The below post describes how you can use a Dynamic Query Library provided by the LINQ team to dynamically construct LINQ queries. 下面的文章描述了如何使用LINQ团队提供的动态查询库来动态构造LINQ查询。

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Why not have a separate method that takes an Expression<Func<Product,bool>> as a parameter. 为什么不使用将Expression<Func<Product,bool>>作为参数的单独方法。 Then build the predicate outside the method and pass it as a parameter. 然后在方法外部构建谓词,并将其作为参数传递。

IQueryable<Product> SearchProducts (Expression<Func<Product,bool>> selector )
{
    return dataContext.Products.Where( selector );
}

used as 用作

var selector = PredicateBuilder.False<Product>()
                               .Or( p => p.Name == name )
                               .Or( p => p.Vendor == vendor );

products = repository.SearchProducts( selector );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM