I need a custom expression which works in Entity Framework. The method should have this signature:
var ids = new List<int> { 1, 2, 3 };
Context.FooEntities.WithoutId(e => e.Id, ids);
That should give me all Foo
entities which do not have Id
properties that match those in the list.
My attempt is based on an existing example here.
public static IQueryable<T> WithoutId<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.Not(
Expression.Call(
Expression.Constant(ids),
typeof(ICollection<int>).GetMethod("Contains"),
Expression.Property(parameter, property))),
parameter);
return entities.Where(expression);
}
The problem is when ids
is empty then it returns all entities. It should return no entities.