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.
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);
}