0
我有一個功能類似一個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.
我其實並不想改變方法signaure,我就拉澤r改變了對它的呼籲,但我不確定在WhereIn<>
的括號之間應該放入什麼。
我把其中擴展在一個名爲擴展靜態類,所以我沒有看到x.WhereIn,所以它有點像Extensions.WhereIn。 – Xaisoft
如果你沒有看到x.WhereIn這意味着要麼你不具備擴展類的命名空間using語句,或X是不是類型的ObjectQuery。 –
RobSiklos
x是我個案中的Person實體。 – Xaisoft