Skip to content

Consider conversions between Integers and Enums  #162

Closed
@BlaiseD

Description

@BlaiseD

Discussed in #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<Car, DbCar>().ReverseMap();
	}
}
internal static Expression<Func<DbCar, bool>> 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<Expression<Func<DbCar, bool>>>(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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions