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.

我实际上不想更改方法签名,我宁愿更改对它的调用,但我不确定在WhereIn<>.

4

1 回答 1

1

我认为您调用扩展方法是错误的。

试试这样:

predicate = predicate.And(x => x.WhereIn(x.id, Ids));
于 2013-05-30T15:44:59.987 回答