| | 1 | | using System; |
| | 2 | | using System.Linq.Expressions; |
| | 3 | |
|
| | 4 | | namespace Plainquire.Filter; |
| | 5 | |
|
| | 6 | | /// <summary> |
| | 7 | | /// Extension methods for <see cref="Expression"/>. |
| | 8 | | /// </summary> |
| | 9 | | internal static class ExpressionExtensions |
| | 10 | | { |
| | 11 | | /// <summary> |
| | 12 | | /// Gets the name of a first level property. |
| | 13 | | /// </summary> |
| | 14 | | /// <typeparam name="TEntity">The type of the class that declares <typeparamref name="TProperty"/>.</typeparam> |
| | 15 | | /// <typeparam name="TProperty">The type of the property.</typeparam> |
| | 16 | | /// <param name="property">The property to get the name for.</param> |
| | 17 | | /// <exception cref="ArgumentException">Given property must be a first level property access expression like person |
| | 18 | | public static string GetPropertyName<TEntity, TProperty>(this Expression<Func<TEntity, TProperty>> property) |
| | 19 | | { |
| 10212 | 20 | | var body = UnboxBody(property); |
| | 21 | |
|
| 10212 | 22 | | if (body is not MemberExpression { Expression: ParameterExpression } memberExpression) |
| 1 | 23 | | throw new ArgumentException("Given property must be a first level property access expression like person => |
| | 24 | |
|
| 10211 | 25 | | return memberExpression.Member.Name; |
| | 26 | | } |
| | 27 | |
|
| | 28 | | private static Expression UnboxBody<TEntity, TProperty>(this Expression<Func<TEntity, TProperty>> property) |
| | 29 | | { |
| 10212 | 30 | | if (property.Body is UnaryExpression { NodeType: ExpressionType.Convert } convert) |
| 0 | 31 | | return convert.Operand; |
| 10212 | 32 | | return property.Body; |
| | 33 | | } |
| | 34 | | } |