如何在c#表达式中从属性调用属性
本文关键字:从属性 调用 属性 表达式 | 更新日期: 2023-09-27 18:10:53
我有3个班级
AutoYearMake{
int Year { get; set; }
string Make { get; set; }
}
AutoModel{
IAutoYearMake AutoYearMakeParent { get; set; }
string Model { get; set; }
}
AutoTrim{
IAutoModel AutoModelParent { get; set; }
string Trim { get; set; }
}
我需要创建一个查询数据库。我怎样才能动态地得到这样一个表达式:
Expression<Func<AutoTrim, bool>> expression = expression = t => t.AutoModelParent.AutoYearMakeParent.Year == year.Value
&& t.AutoModelParent.AutoYearMakeParent.Make
== make && t.AutoModelParent.Model == model;
这是我的代码。它不工作。
ParameterExpression parameter = Expression.Parameter(typeof (AutoTrim), "a");
MemberExpression yearProp = Expression.Property(parameter, "AutoModelParent.AutoYearMakeParent.Year");
MemberExpression makeProp= Expression.Property(parameter, "AutoModelParent.AutoYearMakeParent.Make");
MemberExpression modelProp= Expression.Property(parameter, "AutoModelParent.Model");
Expression right = Expression.Constant(2014);
Expression e1 = Expression.Equal(yearProp, right);
right = Expression.Constant("make");
Expression e2 = Expression.Equal(makeProp, right);
right = Expression.Constant("model");
Expression e3 = Expression.Equal(modelProp, right);
Expression predicateBody = Expression.AndAlso(e1, e2);
Expression final = Expression.AndAlso(e1, e2);
如何解决这个问题?我试着用Expression.Call。
Expression.Property()
方法的第一个参数是应该访问属性的对象。如果你想从参数t
访问属性AutoModelParent
,你可以使用:
Expression.Property(parameter, "AutoModelParent")
所以,如果你想访问参数t的AutoModelParent属性的Model属性你可以输入:
Expression.Property(Expression.Property(parameter, "AutoModelParent"), "Model")
考虑这个解决方案:
private static MemberExpression GetPropertyPathAccessor(Expression parameter, string path)
{
return (MemberExpression) path.Split('.').Aggregate(parameter, Expression.Property);
}
或者如果你不喜欢一行字
private static MemberExpression GetPropertyPathAccessor(Expression parameter, string path)
{
Expression current = parameter;
foreach (var propertyName in path.Split('.'))
{
current = Expression.Property(current, propertyName);
}
return (MemberExpression)current;
}
那么你可以使用:
MemberExpression yearProp = GetPropertyPathAccessor(parameter, "AutoModelParent.AutoYearMakeParent.Year");
这个怎么样?
在expFunc中有了Func<>之后,你可以马上使用它。
var argParam = Expression.Parameter(typeof(AutoTrim), "s");
var expFunc = Expression.Lambda<Func<AutoTrim, bool>>(
Expression.AndAlso(
Expression.AndAlso(
Expression.Equal(
Expression.Property(Expression.Property(Expression.Property(argParam, "AutoModelParent"), "AutoYearMakeParent"), "Year"),
Expression.Constant(year.Value)),
Expression.Equal(
Expression.Property(Expression.Property(Expression.Property(argParam, "AutoModelParent"), "AutoYearMakeParent"), "Make"),
Expression.Constant(make))
),
Expression.Equal(
Expression.Property(Expression.Property(argParam, "AutoModelParent"), "Model"),
Expression.Constant(model))
),
argParam
).Compile();
当然你也需要这些(只是示例值):
int? year = 2000;
string make = "BMW";
string model = "6";