使用类型转换动态构建表达式树
本文关键字:表达式 构建 动态 类型转换 | 更新日期: 2023-09-27 18:11:27
(已编辑(:
我有我的课:
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;}
}
我可以这样查询合同月份(使用员工作为基本类型(:
第一种情况:
r => (r.Employee as ContractEmployee).Amount > 10000
更正:
r => (r.Employee is ContractEmployee) && r.Amount > 10000
第二种情况:
_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";不属于类";雇员";。
如何使用表达式树将Employee类型转换为ContractEmployee:r=>(r.Employee as ContractEmployees(。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))
)