从属性名称的字符串创建表达式? [英] Creating an expression from the string of a property name?
问题描述
我正在尝试基于某些JSON创建查询,目前我已将JSON解析为一组规则,每个规则均包含字段名称,比较类型(=,>等)和比较.
我遇到的问题是将其从该规则传递到IQueryable对象,我想我需要使用反射并以某种方式构建表达式树,但是我不确定采用正确的方法... >
假设我有:
public class Order : BaseEntity
{
public int OrderID{ get; set; }
}
我的规则是:
public class Rule
{
public string field { get; set; }
public Operations op { get; set; }
public string data { get; set; }
}
运行它,我得到:
field = "OrderID"
op = "eq"
data = "123"
我有使用签名来解析它的方法:
public IQueryable<T> FilterObjectSet<T>(IQueryable<T> inputQuery) where T : class
作为此方法的一部分,我想做:
inputQuery = inputQuery.Where(o => propertyInfo.Name == rule1.data);
这是行不通的,因为它基本上只生成sql"OrderID" ="123",这显然是错误的,我需要它从inputQuery中获取与propertyInfo.Name同名的列名并构建查询这样...
希望有道理吗?有什么建议吗?
我想我要问的是将一个字符串(因为我可以很容易地从规则中构建一个字符串)转换为一个表达式,也许使用Dynamic LINQ?
最后,我使用了在Guthrie博客上找到的Dynamic Linq库:
使用此方法,我可以正确解析并使用规则中内置的参数
I am trying to create a query based on some JSON, I currently have the JSON parsed into a set of rules, each rule contains the name of the field, the type of comparison (=, > etc) and the value to compare.
The issue I am having is getting it from that rule, to an IQueryable object, I am guessing I need to use reflection and somehow build the expression tree, but I'm not sure on the right approach...
Assuming I have:
public class Order : BaseEntity
{
public int OrderID{ get; set; }
}
and I have the rule which is:
public class Rule
{
public string field { get; set; }
public Operations op { get; set; }
public string data { get; set; }
}
Running it I get:
field = "OrderID"
op = "eq"
data = "123"
I have the method to parse it with the signature:
public IQueryable<T> FilterObjectSet<T>(IQueryable<T> inputQuery) where T : class
As part of this method I want to do:
inputQuery = inputQuery.Where(o => propertyInfo.Name == rule1.data);
This doesn't work because it basically just generates the sql "OrderID" = "123" which is obviously wrong, I need it to take the column name from inputQuery that has the same name as propertyInfo.Name and build the query that way...
Hope that made sense? Any suggestions?
Edit: I guess what I am asking is to convert a string (Because I can build one pretty simply from the rule) to an expression, maybe using Dynamic LINQ?
In the end I used a Dynamic Linq library I found on Guthrie's Blog:
Using this I was able to properly parse out and use the parameters I had built into the rules
这篇关于从属性名称的字符串创建表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!