我试图在过去使用过Automapper的ValueInjector。我想将一个枚举转换为另一个只有枚举名称不同但属性名称和值相同的枚举。
public enum GenderModel
{
NotSpecified = 0,
Male = 1,
Female = 2
}
public enum GenderDto
{
NotSpecified = 0,
Male = 1,
Female = 2
}
然后我试图像这样映射
var model = GenderModel.Male;
var dto = GenderDto.NotSpecified;
dto.InjectFrom(model);
我希望在dto对象中获得Male,但它仍然设置为NotSpecified。
我错过了什么?请指导。
答案 0 :(得分:2)
在我看来,ValueInjecter
无法映射enum, struct, int, double
等值类型。或者不需要映射值类型。它只能帮助映射班级类型'具有相同名称和类型的属性。为了映射这个例子的枚举,我建议,
var model = GenderModel.Male;
var dto = GenderDto.NotSpecified;
dto = (GenderDto)model;
如果枚举嵌套在特定类中,则默认的ValueInjecter无法映射GenderModel
和GenderDto
,因为它们的类型不同。所以我们可以通过客户ValueInjecter实现它。这是我的测试代码,希望它可以提供帮助。
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;
}
}
主要功能代码:
static void Main(string[] args)
{
var person1 = new Person1(){Gender = GenderModel.Male};
var person2 = new Person2(){Gender = GenderDto.Female};
person2.InjectFrom<EnumMapInjection>(person1);
}
答案 1 :(得分:0)
类型转换是您的解决方案
dto = (GenderDto)model;