Quick question on how to get even more out of 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)); with something allowing searching by fieldToSearch?
Is this possible, is it a bad idea?
For what you want to do, Dynamic Linq might be more appropriate.
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.
Traditionally these types of dynamic query scenarios are often handled by concatenating strings together to construct dynamic SQL queries. Recently a few people have sent me mail asking how to handle these types of scenarios using LINQ. The below post describes how you can use a Dynamic Query Library provided by the LINQ team to dynamically construct LINQ queries.
Why not have a separate method that takes an Expression<Func<Product,bool>>
as a parameter. 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 );
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.