创建动态Linq查询表达式时出错

时间:2015-11-10 05:10:09

标签: c# linq linq-expressions

    PropertyInfo[] All_prop = Get_All_prop2(Model);
    //------Get Properties has Value-----
    foreach (PropertyInfo property in All_prop)
    {
        //--Check Has Value Property
        if (property.GetValue(this, null) != null)
        {
            IQueryable<DAL_BankWebApp.TBUSER> Query = cntx.TBUSERs.Select(x => x);
            //--Create Expression Of Property
            ParameterExpression pe = Expression.Parameter(typeof(string), property.Name);

            ConstantExpression Constant = Expression.Constant(property.GetConstantValue());
            Expression Contain = Expression.Call(pe, typeof(string).GetMethod("Contains", new[] { typeof(string) }), Constant);
            //----Create Where
            MethodCallExpression whereCallExpression = Expression.Call(
                typeof(Queryable),
                "Where",
                new Type[] { Query.ElementType },
                Query.Expression,
                Expression.Lambda<Func<string, bool>>(Contain, new ParameterExpression[] { pe }));

            IQueryable<DAL_BankWebApp.TBUSER> results = Query.Provider.CreateQuery<DAL_BankWebApp.TBUSER>(whereCallExpression);
            Result = results;
        }
    }

我得到以下错误At =&gt; if(property.GetValue(this,null)!= null)

base {“Object与目标类型不匹配。”} System.ApplicationException {System.Reflection.TargetException}

1 个答案:

答案 0 :(得分:0)

我解决了: if(property.GetValue(Model,null)!= null)