在构建动态 linq 表达式时,我似乎无法访问 Dictionary<string, object> 值

I can't seem to be able to access a Dictonary<string, object> values while building a dynamic linq expression

我正在尝试使用 MongoDriver 在 asp.net 核心中为 MongoDB 生成一个 linq 表达式,但我无法使用表达式生成器访问字典的运行时值。提前致谢!

private Expression<Func<Dictionary<string, object>, bool>> GenerateWhereExpression(Dictionary<string, object> filterParams)
{
    var pe = Expression.Parameter(typeof(Dictionary<string, object>), "x");
    var dictPropery = Expression.PropertyOrField(pe, "name"); // Dictonary value with respect to the name key
    var methodCall = Expression.Call(dictPropery, typeof(string).GetMethod("Contains"), Expression.Constant(filterParams["name"], typeof(string)));
    var lambda = Expression.Lambda<Func<Dictionary<string, object>, bool>>(methodCall, pe);
    return lambda;
}

我要完成的是查询的 where 子句以获取报告的所有数据。

Expresssiom,应作为该方法的结果创建,应如下所示:

x => ((string)x["name"]).Contains(term) 

好的,你需要这样改变你的方法:

private Expression<Func<Dictionary<string, object>, bool>> 
                     GenerateWhereExpression(Dictionary<string, object> filterParams)
{
    var pe = Expression.Parameter(typeof(Dictionary<string, object>), "x");
    // it is call of x.getItem("name") what is the same as x["name"]
    var dictPropery = Expression.Call(pe, 
           typeof(Dictionary<string, object>).GetMethod("get_Item"), 
           Expression.Constant("name")); 

    //cast to ((string)x.getItem("name"))
    var castProperty = Expression.Convert(dictPropery, typeof(string));
    var methodCall = Expression.Call(castProperty, 
                    typeof(string).GetMethod("Contains"), 
                    Expression.Constant(filterParams["name"], typeof(string)));
    var lambda = Expression.Lambda<Func<Dictionary<string, object>, bool>>(methodCall, pe);
    return lambda;
}

我已经用我的 mongodriver 测试了它,它似乎可以工作。 实际上,要从字典中获取项目,您需要调用 Item 属性 (Building Expression Tree Using a Parameter's Indexer)。但是要么我用错了,要么 MongoDb 驱动程序无法正确翻译它,所以我正在调用 get_Item 方法,这是一回事。