public class ClassEntityA
{
public int Id { get; set; }
public string Text { get; set; }
}
public class ClassEntityB
{
public int Id { get; set; }
public string Text { get; set; }
public Nullable<ClassEntityA> EntityA { get; set; }
}
// I need to do the following query in Ado Entity. That query works in Linq To Sql, but not suported in Linq To Entity
list<int> list = new List<in>() { 1, 2, 3 };
var itens = DbContext.ClassEntityB.Where(c => (list.Contains(c.EntityA.Id) == false || c.EntityA == null);
// i Found a Half Solution to do that in Linq To Entity doing that:
// But Here i can do the second test (OR c.EntityA == null). How can i do That?
list<int> list = new List<in>() { 1, 2, 3 };
var itens = DbEntities.ClassEntityB.WhereNotIn(c => c.EntityA.Id, list.AsEnumerable<int>())
#region Where Not In
private static Expression<Func<TElement, bool>>
GetWhereNotInExpression<TElement, TValue>(
Expression<Func<TElement, TValue>> propertySelector,
IEnumerable<TValue> values)
{
ParameterExpression p =
propertySelector.Parameters.Single();
if (!values.Any())
{
return e => true;
}
var unequals = values.Select(value =>
(Expression)Expression.NotEqual(
propertySelector.Body,
Expression.Constant(value, typeof(TValue))
)
);
var body = unequals.Aggregate<Expression>(
(accumulate, unequal) => Expression.And(accumulate, unequal));
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
public static IQueryable<TElement>
WhereNotIn<TElement, TValue>(this IQueryable<TElement> source,
Expression<Func<TElement, TValue>> propertySelector,
params TValue[] values)
{
return source.Where(GetWhereNotInExpression(
propertySelector, values));
}
public static IQueryable<TElement>
WhereNotIn<TElement, TValue>(this IQueryable<TElement> source,
Expression<Func<TElement, TValue>> propertySelector,
IEnumerable<TValue> values)
{
return source.Where(GetWhereNotInExpression(
propertySelector, values));
}
#endregion