简体   繁体   English

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

[英]How can I modify this extension method accept two string parameters?

I have the following extension method which behaves like a SQL IN : 我有以下行为类似于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);
        }

The problem is that when I call it like this: 问题是当我这样称呼它时:

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

It gives me an error: 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. 它给我一个错误: 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. 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.

I actually don't want to change the method signaure, I would rather change the call to it, but I am not sure what to put in between the brackets of WhereIn<> . 实际上,我不想更改方法的标志,我希望更改对它的调用,但是我不确定在WhereIn<>括号之间放置什么。

I think you're calling the extension method wrong. 我认为您将扩展方法称为错误。

Try like this: 尝试这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM