Linq to entity 动态生成where in

问题背景:

        public IQueryable<T_Bas_PlanInfo> GetT_Bas_PlanInfoByCondition(List<string> conditions)
        {
            var results = this.ObjectContext.T_Bas_PlanInfo
                .Where(e => conditions.Any(e2 => e.plangeneral.Contains(e2)));

            return results;
        }

在T_Bas_PlanInfo中的plangeneral列中查找包含conditions中任意元素的项,结果返回空(实际应该非空)。

解决方案:

对于conditions这种动态数组,需要表达式树动态生成查询语句。

扩展wherein

       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");
            ParameterExpression p = selector.Parameters.Single();

            if (!collection.Any()) return query;

            IEnumerable<Expression> equals = collection.Select(value =>
               (Expression)Expression.Call(selector.Body,
                    typeof(string).GetMethod("Contains"),
                    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));
        }

        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);
        }

调用方式如下:

        public IQueryable<T_Bas_PlanInfo> GetT_Bas_PlanInfoByCondition(List<string> conditions)
        {
            var results = this.ObjectContext.T_Bas_PlanInfo
                .WhereIn(e => e.plangeneral, conditions);

            return results;
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值