How to map an int to its enum description using AutoMapper during a queryable projection?

后端 未结 1 1256
一向
一向 2021-01-03 10:13

Here is the enum extension method to get its description attribute.

public static string GetDescription(this Enum enumeration)
{
    if (enumeration == null)         


        
1条回答
  •  别那么骄傲
    2021-01-03 10:58

    If you check out the signature of the MapFrom method, you'll notice that one of the overloads takes a parameter of type Expression>.

    This suggests that you could write a method which builds an expression tree from ternary expressions that can convert any possible value of your enum to its appropriate string. AutoMapper would then convert this into the appropriate SQL expression via LINQ.

    Here's an example which just uses the Enum names themselves: you should be able to adapt it straightforwardly to use your Descriptions:

    public static class EnumerableExpressionHelper
    {
        public static Expression> CreateEnumToStringExpression(
            Expression> memberAccess, string defaultValue = "")
        {
            var type = typeof(TMember);
            if (!type.IsEnum)
            {
                throw new InvalidOperationException("TMember must be an Enum type");
            }
    
            var enumNames = Enum.GetNames(type);
            var enumValues = (TMember[])Enum.GetValues(type);
    
            var inner = (Expression)Expression.Constant(defaultValue);
    
            var parameter = memberAccess.Parameters[0];
    
            for (int i = 0; i < enumValues.Length; i++)
            {
                inner = Expression.Condition(
                Expression.Equal(memberAccess.Body, Expression.Constant(enumValues[i])),
                Expression.Constant(enumNames[i]),
                inner);
            }
    
            var expression = Expression.Lambda>(inner, parameter);
    
            return expression;
        }
    }
    

    You would use it as follows:

    CreateMap()
                .ForMember(e => e.ReviewStatus,
                    c => c.MapFrom(EnumerableExpressionHelper.CreateEnumToStringExpression((Entry e) => e.ReviewStatus)))
    

    0 讨论(0)
提交回复
热议问题