[英]Building expression tree dynamically with typecasting
(Edited): (编辑):
I have my 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;}
}
I can query Contract month like this (Using Employee as base type): 我可以这样查询合约月份(使用员工作为基本类型):
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);
I need to create this expression 我需要创建这个表达式
r => (r.Employee as ContractEmployee).ContractMonth > 10
dynamically. 动态。
Suppose, I get this string "Employee.ContractMonth > 10" and it will be known that I need to convert it onto ContractEmployee while coding. 假设,我得到这个字符串“Employee.ContractMonth> 10”,我知道我需要在编码时将它转换为ContractEmployee。
I can convert this into an expression as follows: 我可以将其转换为表达式,如下所示:
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);
The above code will not work because "ContractMonth" does not belong to the class "Employee". 上述代码无效,因为“ContractMonth”不属于“Employee”类。
How can I typecast Employee as ContractEmployee using Expression Tree: r => (r.Employee as ContractEmployee).ContractMonth > 10
如何使用表达式树将Employee强制转换为ContractEmployee:r =>(r.Employee as ContractEmployee).ContractMonth> 10
Thanks 谢谢
You are trying to access property on the wrong object. 您正在尝试访问错误对象上的属性。
You have 你有
r => (r.Employee as ContractEmployee).Amount > 10000
While it should be: 虽然它应该是:
r => (r.Employee is ContractEmployee) && r.Amount > 10000
I'm leaving it to you to build expression from this lambda 我要把它留给你来建立这个lambda的表达
Something like this: 像这样的东西:
Expression.And(
Expression.TypeIs(Expression.Parameter(typeof(Employee), "r"), typeof(ContractEmployee)),
Expression.GreaterThan(Expression.Property(Expression.Parameter(typeof(Employee), "r"), "Ammount"), Expression.Constant(10000))
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.