public class BaseViewModel
{
public MyEnum EnumValue {get;set;}
public string PropA { get; set; }
}
public class Enum1ViewModel : BaseViewModel
{
public string PropB {get; set;}
}
public class Enum2ViewModel : BaseViewModel
{
public string PropC {get; set;}
}
public class Enum3ViewModel : BaseViewModel
{
public string PropD {get; set;}
}
public enum MyEnum
{
Value1,
Value2,
Value3
}
public class MyEntity
{
public MyEnum EnumValue {get; set;}
public string PropA {get;set;}
public string PropB {get;set;}
public string PropC {get;set;}
public string PropD {get;set;}
public string PropE {get;set;}
}
public class MapperProfile : Profile
{
public MapperProfile()
{
CreateMap<Enum1ViewModel, MyEntity>()
.ForMember(m => m.EnumValue, o => o.UseValue(MyEnum.Value1)
.ForMember(m => m.PropC, o => o.Ignore())
.ForMember(m => m.PropD, o => o.Ignore())
.ForMember(m => m.PropE, o => o.Ignore());
CreateMap<Enum2ViewModel, MyEntity>()
.ForMember(m => m.EnumValue, o => o.UseValue(MyEnum.Value2)
.ForMember(m => m.PropB, o => o.Ignore())
.ForMember(m => m.PropD, o => o.Ignore())
.ForMember(m => m.PropE, o => o.Ignore());
CreateMap<Enum3ViewModel, MyEntity>()
.ForMember(m => m.EnumValue, o => o.UseValue(MyEnum.Value3)
.ForMember(m => m.PropB, o => o.Ignore())
.ForMember(m => m.PropC, o => o.Ignore())
.ForMember(m => m.PropE, o => o.Ignore());
// Question: How do I do the reverse mapping??
}
}
我在twitter上向吉米Bogard問了這個問題,但我認爲答案可能會幫助更多的人,然後只是我自己。AutoMapper:根據枚舉值將類映射到視圖模型
如果我在Jimmy的回答發佈之前,或者你們任何一個人,我會自己回答。
代碼中的問題是什麼? –