Expression<Func<TEntity, object>> expression
を使う。
プロパティ名を取得できれば、ASP .NET MVC のHTMLヘルパ作りなどが捗る。
Expressionの使い方は、詳しい資料を別途参考にしてください。
ExpressionExtentions.cs
public static class ExpressionExtentions
{
/// <summary>
/// MemberExpressionへの変換(string以外の型に対応するため)
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static MemberExpression ToMemberExpression(LambdaExpression expression)
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression != null) return memberExpression;
var unaryExpression = expression.Body as UnaryExpression;
if (unaryExpression != null) return unaryExpression.Operand as MemberExpression;
return memberExpression;
}
/// <summary>
/// プロパティ名を取得する
/// </summary>
/// <param name="expression"></param>
/// <param name="names"></param>
/// <returns></returns>
public static IEnumerable<string> GetPropertyNames(this LambdaExpression expression)
{
return GetPropertyNames(ToMemberExpression(expression));
}
/// <summary>
/// プロパティ名を取得する(再帰で取得)
/// </summary>
/// <param name="memberExpression"></param>
/// <param name="names"></param>
/// <returns></returns>
public static IEnumerable<string> GetPropertyNames(MemberExpression memberExpression, IList<string> names = null)
{
if (names == null)
{
names = new List<string>();
}
if (memberExpression.Expression is MemberExpression)
{
GetPropertyNames(memberExpression.Expression as MemberExpression, names);
}
names.Add(memberExpression.Member.Name);
return names;
}
}
使い方
HtmlHelper.cs
public static MvcHtmlString ImageLinkFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
var propertyNames = expression.GetPropertyNames();
/*色々処理*/
}
Index.cshtml
@Html.ImageLinkFor(x=>x.Image)