Skip to content

Instantly share code, notes, and snippets.

@mvalipour
Last active December 22, 2015 10:08
Show Gist options
  • Save mvalipour/b9bbd716b3752871d5a2 to your computer and use it in GitHub Desktop.
Save mvalipour/b9bbd716b3752871d5a2 to your computer and use it in GitHub Desktop.
Run ID search on an EntityFramework query in a way that results in parameterized sql `IN` clause
public static IQueryable<T> WhereIdIsAnyOf<T>(this IQueryable<T> source, int[] ids)
{
var parameter = Expression.Parameter(typeof(T));
Expression expression = null;
foreach(var value in ids)
{
// NOTE: here instead of refering to the id directly (via Expression.Constant)
// an intermediary object is used to refer to the value
// to avoid compile-time constant folding
// that will result in the value NOT being parametarized
// .
var valueObject = new { Value = value };
var idExpression = Expression.PropertyOrField(Expression.Constant(valueObject), "Value");
var equityExpression = Expression.Equal(Expression.Property(parameter, "ID"), idExpression);
expression = expression == null ? equityExpression : Expression.OrElse(expression, equityExpression);
}
return expression == null ?
source :
source.Where(Expression.Lambda<Func<T, bool>>(expression, parameter));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment