Linq其中扩展方法变量p错误

时间:2014-05-06 08:59:29

标签: c# sql linq extension-methods

我为其中写了这个扩展方法;

public static IQueryable<T> WhereIn<T, TValue>(this IQueryable<T> query,
                        IEnumerable<TValue> values, params Expression<Func<T, TValue>>[] valueSelectors)
        {            
            return query.Where(BuildContainsExpression(values, valueSelectors));

        }
        private static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(
                        IEnumerable<TValue> values, params Expression<Func<TElement, TValue>>[] valueSelector)
        {
            if (null == valueSelector)
            {
                throw new ArgumentNullException("valueSelector");
            }
            if (null == values)
            {
                throw new ArgumentNullException("values");
            }

            Expression<Func<TElement, bool>> predicate = null;

            for (int i = 0; i < valueSelector.Count(); i++)
            {
                var param = valueSelector[i];
                ParameterExpression genericParameter = param.Parameters[0];

                TValue[] enumerable = values as TValue[] ?? values.ToArray();
                if (!enumerable.Any())
                {
                    return e => false;
                }

                if (!enumerable.Any())
                {
                    return e => false;
                }
                IEnumerable<Expression> equals = enumerable.Select(value => (Expression)Expression.Equal(param.Body, Expression.Constant(value, typeof(TValue))));
                Expression body = equals.Aggregate(Expression.Or);
                Expression<Func<TElement, bool>> partialPredicate = Expression.Lambda<Func<TElement, bool>>(body, genericParameter);

                if (predicate == null)
                    predicate = partialPredicate;
                else
                {
                    var orElse = Expression.OrElse(predicate.Body, partialPredicate.Body);
                    predicate = Expression.Lambda<Func<TElement, bool>>(orElse, genericParameter);
                }

            }

            if (predicate != null)
                return predicate;
            return null;
        }

predicate result is = {p => ((((Convert(p.Id) == 1) Or (Convert(p.Id) == 3)) Or (Convert(p.Id) == 5)) OrElse (((p.MemberId == 1) Or (p.MemberId == 3)) Or (p.MemberId == 5)))}

public class OrderDto { public string Id {get;set;} } 

我的意见是:

var list = new List<int?> {1, 3, 5}; 
var orderList = Entity.Order.AsQueryable().WhereIn(list, p => p.Id, p => p.MemberId).Select(t => new OrderDto {Id =t.Id}); –

但是我得到了这个错误;

  

变量&#39; p&#39;类型&#39; OrderDto&#39;引用范围&#39;&#39;,但未定义

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您正在重复使用给定表达式中的参数。

ParameterExpression genericParameter = param.Parameters[0];

创建新表达式时,还必须创建新参数。

ParameterExpression genericParameter = new ParameterExpression(...);

有关主人的更多信息,请参阅here