1

出于我的项目的目的,我需要对实体进行一些 linq 查询,我正在使用表达式工厂方法来构建动态过滤谓词。

考虑到这段代码:

public class mother{
  public int age {get; set;}
  public string name {get; set;}
  public child child {get; set;}
}

public class child{
  public int age {get; set;}
  public string name {get; set;}
}

//predicate builder
public static Expression<Func<T, bool>> GetChildNamePredicat<T>(){
  var param = Expression.Parameter(typeof(T), "param");

  // age property of mother class
  var motherAgeProperty = Expression.MakeMemberAccess(param, typeof(T).GetProperty("age"));

  // name property of child class
  var motherChildProperty = Expression.MakeMemberAccess(param, typeof (t).GetProperty("child"));
  var childNameProperty = Expression.MakeMemberAccess(motherChildProperty , typeof (child).GetProperty("name "));

   BinaryExpression motherAgeCondition;
   BinaryExpression childNameCondition;

  //building condition mother age >= 40 and child name = junior
  var motherAgeConst = Expression.Constant(40, typeof(int));
  var childNameConst = Expression.Constant("junior", typeof(string));
  motherAgeCondition = Expression.GreaterThanOrEqual(motherAgeProperty, motherAgeConst);
  childNameCondition= Expression.Equal(childNameProperty, childNameConst);
  var mergeCondition = Expression.AndAlso(motherAgeCondition , childNameCondition);

  //return expression
  return Expression.Lambda<Func<T, bool>>(mergeCondition , param);
}

var myPredicate = GetChildNamePredicat<mother>();

此代码编译成功,但似乎不是功能性的,没有结果...通过在“myPredicate”上使用变量的间谍,我可以看到像这样的 lambda 调试视图:

.Lambda
#Lambda1<System.Func`2[myNameSpace.mother,System.Boolean]>(myNameSpace.mothe $e) { $e.age >= 40 &&  ($e.child).name == "junior" }

($e.child) ...太奇怪了

您是否知道另一种解决方案或/并且对从母亲参数访问子名称属性有任何想法?

谢谢提前!

4

0 回答 0