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 Articles
- Inject param value for TDelegate in Expression<TDelegate> and reduce expression
- Value cannot be null. Parameter name: source
- Access the value of a member expression
- How to resolve Value cannot be null. Parameter name: source in linq?
- .NET Entity Framework - Using .Contains() to find a byte value in a Where expression
- Get the parameter value from a Linq Expression
- LINQ, simplifying expression - take while sum of taken does not exceed given value
- passing dynamic expression to order by in code first EF repository
- Linq expression to set all values of an array to a given value
- Check if a String value contains any number by using Lambda Expression
- How to get a value out of a Span<T> with Linq expression trees?
- 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
- How to convert dynamic value to type value in expression
- Execute expression on another IQueryable source
- LINQ Source Code Available
- Replace parameter value in Expression Tree
- .NET 4 Code Contracts: "requires unproven: source != null"
- Lambda expression to return one result for each distinct value in list
- Linq expression to find the max value of a List<List<int>>?
- SQL Trigger is trying to insert a null value but my C# code is passing int 300?
- The given value of type String from the data source cannot be converted to type int of the specified target column
- How is a variable in a lambda expression given its value
- Combine property selector expression tree and value to create a predicate for EF filtering - create filter from lambda selector and value
- Expression Tree with string assignment and getting value
- C# Change Return Value of Linq Expression
- How to Create a Run-Time Computed (NotMapped) Value in Entity Framework Code First
- Using a linq or lambda expression in C# return a collection plus a single value
- LINQ Expression to extract specific quantity and value of numbers
- Remove non-common items from list
- LINQ Date formatting not allowed to group by a formatted date YearMonth
- LINQ - groupBy with items in several Group
- Linq Query Unable to Return Expected Result
- How to delete a tree in C# Entity Framework Core?
- Use an additional condition/parameter for Enumerable.GroupJoin
- Observable | Subscribe to get only the changed objects
- How to prevent a System.IndexOutOfRangeException in a LINQ WHERE?
- What is wrong with my XDocument save?
- How to implement functional object construction in C#
- How to compare 2 sets of arrays for distinct matches
- Using GroupBy and show different Sums based on conditions - LINQ Lambda Expressions
- Linq - Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement>' to 'System.Collections.Generic.List<string>'
- How do I map List<T1> to List<T2> using LINQ (or otherwise)
- Linq IEnumerable Concat not working for list of objects containing second list as child object
- Left join on two Lists and maintain one property from the right with Linq
- Did XQuery give birth to LINQ?
- Linq: the best overloaded match has some invalid arguments
- Convert SQL to LINQ query to get max
- When mocking Workbook->Worksheets: variable 'p' of type 'Microsoft.Office.Interop.Excel.Workbook' referenced from scope '', but it is not defined