AutoMapper / AutoMapper.Extensions.ExpressionMapping

MIT License
143 stars 39 forks source link

Consider conversions between Integers and Enums #162

Closed BlaiseD closed 1 year ago

BlaiseD commented 1 year ago

Discussed in https://github.com/AutoMapper/AutoMapper.Extensions.ExpressionMapping/discussions/161

Originally posted by **ErikGjers** February 9, 2023 Hi, I am having an issue with the library. I am using it to translate expressions regarding filtering in a database query. Below I have code to illustrate a simple example that causes the issue. ``` internal enum Color { red = 1, green = 2, blue = 3 } ``` ``` internal class Car { public Color Trim { get; set; } } ``` ``` internal class DbCar { public int Trim { get; set; } } ``` ``` internal class CarMap : Profile { public CarMap() { CreateMap().ReverseMap(); } } ``` ``` internal static Expression> TranslateCar() { //Build the expression to translate var param = Expression.Parameter(typeof(Car), "c"); var paramWithProp = Expression.Property(param, nameof(Car.Trim)); var constant = Expression.Constant(Color.green, typeof(Color)); var ex = Expression.NotEqual(paramWithProp, constant); var exLambda = Expression.Lambda(ex, param); //Expression is now {c => c.Trim != Color.green} var mapper = new MapperConfiguration(config => config.AddProfile(new CarMap())).CreateMapper(); var translatedEx = mapper.MapExpression>>(exLambda); return translatedEx; } ``` Calling TranslateCar causes an exception: System.InvalidOperationException: 'The binary operator NotEqual is not defined for the types 'System.Int32' and 'Test+Color'.' This seems to me that the constant part of the expression is not being translated, but the other side of the expression is. I tried a few different ways of mapping the attribute with a custom resolver, but nothing seems to affect the constant part of the expression. One way to fix it is to not have it map from an enum to an int, but I would certainly like to have that as an option for when appropriate. Is this the intended effect? If it is, how do I go about fixing this issue? Thanks for any help.