score:2
Accepted answer
Try:
protected static IQueryable<TQueryResult> AddQueryFilter<TQueryResult, TParam>(
IQueryable<TQueryResult> query, Expression<Func<TQueryResult, TParam, bool>> exp, TParam param)
{
var rewriter = new ExpressionRewriter();
rewriter.Subst(exp.Parameters[1], Expression.Constant(param, typeof(TParam)));
var body = rewriter.Apply(exp.Body);
var lambda = Expression.Lambda<Func<TQueryResult, bool>>(body, exp.Parameters[0]);
return query.Where(lambda);
}
using ExpressionRewriter
from this answer.
score:0
I hope somebody still can be searching for this topic, as me, in fact, so I'd like to suggest the following possibility.
Since .NET 4.0 has been released, you can use built-in expression tree visitors.
Here's an exapmple, which implements required functionality:
private class ExpressionConstantInjector<T, TConstant> : ExpressionVisitor
{
private readonly TConstant toInject;
private readonly ParameterExpression targetParam;
public EntityExpressionListInjector(TConstant toInject)
{
this.toInject = toInject;
targetParam = Expression.Parameter(typeof(T), "a");
}
public Expression<Func<T, bool>> Inject(Expression<Func<T, TConstant, bool>> source)
{
return (Expression<Func<T, bool>>) VisitLambda(source);
}
protected override Expression VisitLambda<T1>(Expression<T1> node)
{
return Expression.Lambda(Visit(node.Body), targetParam);
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (node.Type == typeof (TConstant))
return Expression.Constant(toInject);
return targetParam;
}
}
Usage:
Expression<Func<Entity, List<int>, bool>> expression = (e, ids) => ids.Contains(e.Id);
var filterExpression
= new ExpressionConstantInjector<Entity, List<int>>(new List<int>{1, 2, 3})
.Inject(expression);
// filterExpression is like a => (1, 2, 3).Contains(a.Id)
// filterExpression can be passed to EF IQueryables.
This solution is very local, not really reusable, but quiet simple (nah).
To be honest, [].Contains(id)
is the only case I've tested. But I think it works.
Source: stackoverflow.com
Related Query
- Inject param value for TDelegate in Expression<TDelegate> and reduce expression
- Combine property selector expression tree and value to create a predicate for EF filtering - create filter from lambda selector and value
- Build Dynamic Expression For Linq Where using PropertyInfo and a value
- Linq and the Equality Operator: Expression of type 'System.Int32' cannot be used for parameter of type 'System.Object'
- How to reuse a linq expression for 'Where' when using multiple source tables
- Get Value and Count of that value using LINQ or lambda expression
- Expression to get LINQ with Contains to EF for SQL IN() where on entities child's property equals value
- Using the Select method for dynamic queries and expression trees
- Lambda expression to return one result for each distinct value in list
- Linq query, how to check for a null value and use the value 0 in place of a null?
- Linq check for null and replace null value in orderby
- Avoid extra loop and could not find implementation of query pattern for source type int Select not found
- Expression Tree with string assignment and getting value
- How to use Expression for Linq union and intersect?
- Using C# LINQ Expressions for both Value Types and Reference Types
- Code Example for Add DateTime and TimeSpan in EF query
- LINQ Expression to extract specific quantity and value of numbers
- Stubbing Code for Test With Linq Expressions and Lambdas
- How to unpack an expression tree and check for null values
- Lambda Expression for Many to Many realtionship in C# EF 5 Code First
- Querying for a specific value at the intersection of a Row and a Column in a DataTable
- Grouping a 3 tuple and searching a List of Tuples for a particular value in C#
- Iterating through collection items and checking each property for a valid value
- Code Rewite for tuple and if else statements by using LINQ
- How to check string for null and assign its value in the same line
- Lambda expression arguments for Enumerable and Queryable extension methods
- Reduce the line of code for this LINQ query
- Entity Framework 4.1 simple dynamic expression for object.property = value
- Linq dynamic expression for filtering navigation properties and collections
- Entity Framework Code First override onModelCreating() for TPT Inheritance Screwing Up Identity User and Role Models
More Query from same tag
- Using LINQ to Entities in Insert
- How do I group in memory lists?
- C# LINQ compound ordering on 3 columns
- Checking for each value in Hashset when querying
- Select duplicated items with non duplicates in the same collection
- Query multiple oracle schemas in LINQPAD with IQ driver
- Linq filter by several enumerators
- Expression Trees: Filtered count on navigation property
- Entity Framework 6: virtual collections lazy loaded even explicitly loaded on a query
- access an array element inside a LINQ to Entities set
- EF Code First Insert Objects with One to Many gives exception."Store update, insert, or delete statement affected an unexpected number of rows (0)."
- Can I use an anonymous type for this Linq grouping?
- Linq To SQL Join
- Best way to get all words like @*@ from a string in C#
- How to join tables from IdentityDbContext and ApplicationDbContext
- At least one object must implement IComparable order by
- Selecting count in LINQ
- LINQ to SQL query Multiply two columns and calculate SUM
- 'IQueryable' does not contain a definition for 'OrderByDescending'
- LINQ query in Entity framework 6
- C# Linq List Compare and update lists
- Why doesn't deferred execution cache iterative values?
- Count the number of Attributes in an XML Element
- Doing Some Minor For Each in Linq
- How would I create a viewmodel which contains parent and child data from a selectmany method
- Recursively iterate through subdirectories and add directory to a list, if it contains any file with a specific ending
- Update Entity through a new Object in LINQ to SQL
- sqlLinq Take higher RN number
- Help with a LINQ Query
- How do I join an array of keys with an array of values to a dictionary without a loop?