如何修改此扩展方法接受两个字符串参数?

时间:2013-05-30 15:40:05

标签: c# .net-3.5 linq-to-entities

我有以下扩展方法,其行为类似于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,我宁愿更改对它的调用,但我不确定在WhereIn<>括号之间放什么。

1 个答案:

答案 0 :(得分:1)

我认为您正在调用扩展方法错误。

试试这样:

predicate = predicate.And(x => x.WhereIn(x.id, Ids));