我想出了以下内容。但代码看起来不太好:
public static class GenericHelper<TEntity> {
//This method uses my extension method, but it returns plain property name
public static string GetPropertyName<TProperty>(Expression<Func<TEntity, TProperty>> propertyExpression) {
return propertyExpression.GetPropertyName();
}
//This method is used to return nested property name as dot-separated value
public static string GetPropertyFlattenName<TProperty>(Expression<Func<TEntity, TProperty>> propertyExpression) {
//TODO: check TEntity, if needed. Now it's ignored
var member = propertyExpression.Body as MemberExpression;
if (member == null) {
throw new ArgumentException(String.Format(
"Expression '{0}' refers to a method, not a property.", propertyExpression));
}
var propertyInfo = member.Member as PropertyInfo;
if (propertyInfo == null) {
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.", propertyExpression));
}
//Suppposing it's the only one for this method
var parameter = propertyExpression.Parameters[0].Name;
return propertyExpression.Body.ToString().Replace(string.Format("{0}.", parameter), "");
}
}
我发现无法以更智能和更优雅的方式提取扁平属性名称。
只想指定:第一种方法是这样使用的:
GenericHelper<MyEntity>.GetPropertyName(entity => entity.Property)
但是如果我有一个嵌套属性,比如entity.Property.NestedProperty - 我需要使用我的第二种方法:
GenericHelper<MyEntity>.GetPropertyFlattenName(entity => entity.Property.NestedProperty)
返回&#34; Property.NestedProperty&#34;而不是&#34; NestedProperty&#34;。