Before I forget, for the sake of my own posterity and to test the syntax highlighter plugin I just installed, I would like to take a moment to remind anyone who reads this of a sizable caveat using the Contains() extension method with Entity Framework version 1. Crucially, the method does not generate correct SQL and so the developer was forced to write a compare expression.
Here is that Expression:
static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(
Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
{
if (null == valueSelector) { throw new ArgumentNullException("valueSelector"); }
if (null == values) { throw new ArgumentNullException("values"); }
ParameterExpression p = valueSelector.Parameters.Single();
// p => valueSelector(p) == values[0] || valueSelector(p) == ...
if (!values.Any())
{
return e => false;
}
var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body,
Expression.Constant(value, typeof(TValue))));
var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
Usage is similar to the following:
var assignees = _entities.Admin_Users.Where(BuildContainsExpression<Admin_Users, int>(e => e.Admin_Department_ID.Value,
departmentsToReturn));