You'll have to pass an Expression<Func<T, int>>
instead of an Func<T, int>
and build up the complete expression yourself. This will do the trick:
public static IQueryable<T> WithId<T>(this IQueryable<T> entities,
Expression<Func<T, int>> propertySelector, ICollection<int> ids)
{
var property =
(PropertyInfo)((MemberExpression)propertySelector.Body).Member;
ParameterExpression parameter = Expression.Parameter(typeof(T));
var expression = Expression.Lambda<Func<T, bool>>(
Expression.Call(
Expression.Constant(ids),
typeof(ICollection<int>).GetMethod("Contains"),
Expression.Property(parameter, property)),
parameter);
return entities.Where(expression);
}
When you try to keep your code DRY when working with your O/RM, you will often have to fiddle with expression trees. Here's another fun example.