我有以下扩展方法,用于在LINQ-To-Entities中进行Contains操作:
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));
}
//Optional - to allow static collection:
public static IQueryable<TEntity> WhereIn<TEntity, TValue>
(
this ObjectQuery<TEntity> query,
Expression<Func<TEntity, TValue>> selector,
params TValue[] collection
)
{
return WhereIn(query, selector, (IEnumerable<TValue>)collection);
}
}
当我调用扩展方法来检查一个id列表是否在特定的表中时,它可以正常工作并返回id列表,就像这样:
List<int> Ids = _context.Persons
.WhereIn(x => x.PersonId, PersonIds)
.Select(x => x.HeaderId).ToList();
当我执行下面这条语句时,它报错说LINQ-To-Entities不识别Contains(int32),但是我认为我已经不再使用实体了,而是一个整数集合。
predicate = predicate.And(x=> Ids.Contains(x.HeaderId));
如果我有一个逗号分隔的字符串,例如“1,2,3”,那么以下内容可行:
predicate = predicate.And(x=>x.Ids.Contains(x.HeaderId));
我正在尝试将返回的List创建为逗号分隔的字符串列表,问题在于现在当我执行 predicate = predicate.And(x=>sb.Contains(x.HeaderId.ToString());
时,它会抱怨不喜欢ToString()。
我还尝试过:
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.
List<int>
,我们不介意你如何获取它。问题似乎来自于PredicateBuilder(猜测您使用了这个)。 - Raphaël AlthausIEnumerable<T>.Contains
。就是这样。 - Slauma