我有以下扩展方法,用于在 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));
}
//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));
我正在尝试获取返回的列表并创建逗号分隔的字符串列表,这里的问题是现在当我这样做时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.