You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.8 KiB
48 lines
1.8 KiB
using System;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.Linq;
|
|
using System.Linq.Expressions;
|
|
using System.Reflection;
|
|
|
|
namespace Infrastructure.Extensions
|
|
{
|
|
public static class ExpressionExtensions
|
|
{
|
|
public static string GetPropertyName(this Expression<Func<object, object>> expression)
|
|
{
|
|
if (expression is null)
|
|
{
|
|
throw new ArgumentNullException(nameof(expression));
|
|
}
|
|
return (expression.Body as MemberExpression).Member.Name;
|
|
}
|
|
|
|
//public static string MemberName<T, V>(this Expression<Func<T, V>> expression)
|
|
//{
|
|
// var memberExpression = expression.Body as MemberExpression;
|
|
// if (memberExpression == null)
|
|
// throw new InvalidOperationException("Expression must be a member expression");
|
|
|
|
// return memberExpression.Member.Name;
|
|
//}
|
|
|
|
//public static T GetAttribute<T>(this ICustomAttributeProvider provider)
|
|
// where T : Attribute
|
|
//{
|
|
// var attributes = provider.GetCustomAttributes(typeof(T), true);
|
|
// return attributes.Length > 0 ? attributes[0] as T : null;
|
|
//}
|
|
|
|
public static string GetDisplayAttributeValue<T>(this Expression<Func<T, object>> expression)
|
|
{
|
|
if (expression is null)
|
|
{
|
|
throw new ArgumentNullException(nameof(expression));
|
|
}
|
|
var memberExpression = expression.Body as MemberExpression;
|
|
|
|
var displayAttribute = memberExpression.Member.GetCustomAttributes().FirstOrDefault(o => o.GetType() == typeof(DisplayAttribute));
|
|
return displayAttribute == null ? memberExpression.Member.Name : ((DisplayAttribute)displayAttribute).Name;
|
|
}
|
|
}
|
|
} |