Reputation: 4496
I have in my project one genericRepository with function like this:
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
and this works fine in cases if I want to get elements filtered by only one object. What in the case I need to chain 3-4 where clauses? Is there any way to pass array of expressions if now what is the best way to make this thing work?
After reading your answers and comments I managed to make write this:
Expression<Func<Role, bool>> first = s => s.Id == 1;
Expression<Func<Role, bool>> second = s => s.RoleName != "null";
Expression<Func<Role, bool>> combined = Expression.Lambda<Func<Role, bool>>(Expression.And(first.Body, second.Body));
but this gives me
Additional information: Incorrect number of parameters supplied for lambda declaration
Upvotes: 1
Views: 851
Reputation: 9294
I would advise you to use LinqKit to build the expression from where you are calling this method.
Here's an example:
var predicate = PredicateBuilder.False<Product>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or (p => p.Description.Contains (temp));
}
var products = productRepository.Get(predicate)
Upvotes: 1