h bob h bob - 1 year ago 64
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
entities which do not have
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.Property(parameter, property))),

return entities.Where(expression);

The problem is when
is empty then it returns all entities. It should return no entities.

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download