您的表达式的表达式树如下所示:
.
/ \
. Name
/ \
customer Product
如您所见,没有节点可以代表Product.Name
. 但是您可以使用递归并自己构建字符串:
public static string GetPropertyPath(LambdaExpression expression)
{
return GetPropertyPathInternal(expression.Body);
}
private static string GetPropertyPathInternal(Expression expression)
{
// the node represents parameter of the expression; we're ignoring it
if (expression.NodeType == ExpressionType.Parameter)
return null;
// the node is a member access; use recursion to get the left part
// and then append the right part to it
if (expression.NodeType == ExpressionType.MemberAccess)
{
var memberExpression = (MemberExpression)expression;
string left = GetPropertyPathInternal(memberExpression.Expression);
string right = memberExpression.Member.Name;
if (left == null)
return right;
return string.Format("{0}.{1}", left, right);
}
throw new InvalidOperationException(
string.Format("Unknown expression type {0}.", expression.NodeType));
}