我如何修改这个扩展方法接受两个字符串参数
本文关键字:两个 参数 字符串 方法 扩展 修改 何修改 | 更新日期: 2023-09-27 18:16:19
我有以下扩展方法,其行为类似于SQL IN
:
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);
}
问题是,当我这样调用它时:
predicate = predicate.And(x => WhereIn(x.id, Ids));
它给我一个错误:The type arguments for method 'WhereIn<TEntity,TValue>(System.Data.Objects.ObjectQuery<TEntity>, System.Linq.Expressions.Expression<System.Func<TEntity,TValue>>, params TValue[])' cannot be inferred from the usage. Try specifying the type arguments explictly.
x.id is a Ids are both of type string.
我实际上不想改变方法签名,我宁愿改变对它的调用,但我不确定在WhereIn<>
的括号之间放什么。
我想你把扩展方法调用错了。
试试:
predicate = predicate.And(x => x.WhereIn(x.id, Ids));