开发者

how to build expression tree for multiple level reference property(linked property)?

For example, let's say i have a string property "Document.DocumentType.DocumentCode" with DocumentCode is a nullable decimal type.

How can I build an expression tree for this: x.Document.DocumentType.DocumentCode.开发者_如何学运维GetValueOrDefault() == 4?

For my real case, I won't know exactly what the linked string property will look like or the levels of properties.


Well, that tree is:

  • An equality match, where the left hand side is complicated and the right hand side is a constant expression 4.
  • The LHS is a method call GetValueOrDefault() on (an expression)
  • The expression from the previous step is a property access expression DocumentCode on (an expression)
  • The expression from the previous step is a property access expression DocumentType on (an expression)
  • The expression from the previous step is a property access expression Document on a ParameterExpression

Start from the bottom, and build it up from there. In other words, if you know you're only going to have properties, you'll want to:

  • Split the string by "."
  • Create a ParameterExpression
  • Loop round the set of properties, adding another layer or property access each time, e.g.

    currentExpression = Expression.Property(currentExpression, propertyName);
    
  • Add a method call at to the expression

  • Build an equality comparison using that and whatever constant value you're given
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜