0

I am trying to get my hands on ValueInjector having used Automapper in the past. I want to convert one enum to another where only the enum names are different but the property name and values are same.

 public enum GenderModel
    {
        NotSpecified = 0,
        Male = 1,
        Female = 2
    }

public enum GenderDto
    {
        NotSpecified = 0,
        Male = 1,
        Female = 2
    }

Then I am trying to map like this

var model = GenderModel.Male;
            var dto = GenderDto.NotSpecified;
            dto.InjectFrom(model);

I am expecting to get Male in dto object but it is still set to NotSpecified.

What am I missing? Please guide.

Afraz Ali
  • 2,672
  • 2
  • 27
  • 47

2 Answers2

2

In my opinion, ValueInjecter can not map value types such as enum, struct, int, double. Or no need map for value types. It only help to map class types' properties that have same name and type. To map enum for this example, I suggest,

    var model = GenderModel.Male;
    var dto = GenderDto.NotSpecified;
    dto = (GenderDto)model;

If the enum is nested in the specific class, the default ValueInjecter can not map GenderModel and GenderDto because they are different type. So we can implement it by a customer ValueInjecter. This is my test code here, hope it can help.

public enum GenderModel
{
    NotSpecified = 0,
    Male = 1,
    Female = 2
}

public enum GenderDto
{
    NotSpecified = 0,
    Male = 1,
    Female = 2
}

public class Person1
{
    public GenderModel Gender { get; set; }
}

public class Person2
{
    public GenderDto Gender { get; set; }
}

public class EnumMapInjection:IValueInjection
{
    public object Map(object source, object target)
    {
        StaticValueInjecter.DefaultInjection.Map(source, target);
        if (target is Person2 && source is Person1)
        {
            ((Person2) target).Gender = (GenderDto)((Person1) source).Gender;
        }
        return target;
    }
}

And the Main function code:

    static void Main(string[] args)
    {
        var person1 = new Person1(){Gender = GenderModel.Male};
        var person2 = new Person2(){Gender = GenderDto.Female};
        person2.InjectFrom<EnumMapInjection>(person1); 
    }
Renshaw
  • 1,075
  • 6
  • 12
  • Yes but imagine if this Enum is nested in a Person Class and I am getting a list of person and want to map them to a list of DTO. Unless I can define mapping using ValueInjecter, I would need to iterate list and map the enums manually. – Afraz Ali Oct 12 '17 at 04:44
  • In this case, I suggest a customer Injection inherit from IValueInjection. I can give you an example in my answer. – Renshaw Oct 12 '17 at 05:53
0

Type casting is your solution

dto = (GenderDto)model;
Saleem Kalro
  • 1,046
  • 9
  • 12