h bob h bob - 2 months ago 8
C# Question

An Entity Framework expression to find entities that don't match some property

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.

Answer

How about this? (just as idea, not completed code)

IEnumerable<Entity> Get()
{
    var ids = new[] { 1, 2, 3 };
    if (ids.Length == 0) return Enumerable.Empty<Entity>();

    return MyContext.MyEntities.Where(x=>ids.Contains(x.Id)).ToArray();
}