你表达的表达式树看起来是这样的:
.
/\
. 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));
}
这就是我期待的那种解决方案!在我的项目中对此进行了测试,它的功能如同一种魅力! –