I have the following extension methods in which I use for Content in LINQ-To-Entities:
public static class Extensions { public static IQueryable<TEntity> WhereIn<TEntity, TValue> ( this ObjectQuery<TEntity> query, Expression<Func<TEntity, TValue>> selector, IEnumerable<TValue> collection ) { if (selector == null) throw new ArgumentNullException("selector"); if (collection == null) throw new ArgumentNullException("collection"); if (!collection.Any()) return query.Where(t => false); ParameterExpression p = selector.Parameters.Single(); IEnumerable<Expression> equals = collection.Select(value => (Expression)Expression.Equal(selector.Body, Expression.Constant(value, typeof(TValue)))); Expression body = equals.Aggregate((accumulate, equal) => Expression.Or(accumulate, equal)); return query.Where(Expression.Lambda<Func<TEntity, bool>>(body, p)); }
When I call the extenion method to check if the list of identifiers is in a specific table, it works, and I return a list of identifiers, for example:
List<int> Ids = _context.Persons .WhereIn(x => x.PersonId, PersonIds) .Select(x => x.HeaderId).ToList();
When I execute the following statement, he complains that LINQ-To-Entities is not recogonize Contains (int32), but I thought that I would no longer be against the entity, but a set of ints.
predicate = predicate.And(x=> Ids.Contains(x.HeaderId));
If I have a comma delimited string such as "1,2,3", then the following works:
predicate = predicate.And(x=>x.Ids.Contains(x.HeaderId));
I am trying to return a list and create a list of strings separated by commas, the problem is that now when I do predicate = predicate.And(x=>sb.Contains(x.HeaderId.ToString()); he complains that he don't like ToString ().
I also tried doing:
predicate = predicate.And(x=>Extensions.WhereIn(Ids, x.id));, but it can't resolve WhereIn. It says I must add `<>`, but I am not sure what to add here and how implement it.