使用类型转换动态构建表达式树

Building expression tree dynamically with typecasting

(已编辑):

我有我的 class:

public class Employee
{
    public int Id {get;set;}
    public string Name {get;set;}
}

public class ContractEmployee : Employee
{
    public int ContractMonth {get;set;}
}

public class Remuneration
{
    public int Id {get;set;}
    public Employee Employee {get;set;}
    public int Amount {get;set;}
}

我可以这样查询合同月份(使用员工作为基类型):

1st case:

r => (r.Employee as ContractEmployee).Amount > 10000 

Corrected:

r => (r.Employee is ContractEmployee) && r.Amount > 10000

2nd case:

_context.Remunerations.Where(r => (r.Employee as ContractEmployee).ContractMonth > 10);

我需要创建这个表达式

r => (r.Employee as ContractEmployee).ContractMonth > 10

动态地。

假设,我得到这个字符串“Employee.ContractMonth > 10”,它会知道我需要在编码时将它转换为 ContractEmployee。

我可以将其转换成如下表达式:

PropertyInfo p = typeof(Remuneration).GetProperty("Employee.ContractMonth");
ParameterExpression lhsParam = Expression.Parameter(typeof(Remuneration));
Expression lhs = Expression.Property(lhsParam, p);
Expression rhs = Expression.Constant(Convert.ChangeType("10", pi.PropertyType));
Expression myoperation = Expression.MakeBinary(ExpressionType.GreaterThan, lhs, rhs);

以上代码将不起作用,因为“ContractMonth”不属于 class“Employee”。

How can I typecast Employee as ContractEmployee using Expression Tree: r => (r.Employee as ContractEmployee).ContractMonth > 10

谢谢

您试图访问 属性 错误的对象。

你有

r => (r.Employee as ContractEmployee).Amount > 10000 

虽然应该是:

r => (r.Employee is ContractEmployee) && r.Amount > 10000

我留给你根据这个 lambda 构建表达式

像这样:

Expression.And(
            Expression.TypeIs(Expression.Parameter(typeof(Employee), "r"), typeof(ContractEmployee)),
            Expression.GreaterThan(Expression.Property(Expression.Parameter(typeof(Employee), "r"), "Ammount"), Expression.Constant(10000))
        )