越來越automapper工作(previous question)後,我與另一個問題所困擾(去到另外一個問題,所以第一個就不會太複雜)...Automapper合併對象問題
我有下一類:
public class Model1
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDay { get; set; }
public int Gender { get; set; }
public string NickName { get; set; }
}
public class Model2
{
public bool Married { get; set; }
public int Children { get; set; }
public bool HasPet { get; set; }
}
public class Entity1
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDay { get; set; }
public int Gender { get; set; }
}
public class Entity2
{
public bool Married { get; set; }
public int Children { get; set; }
public bool HasPet { get; set; }
public string NickName { get; set; }
}
這些對象是示意性地類似於我原來的對象,除了名稱和複雜性。
而且AutoMapper配置類(從Global.asax中稱爲):
public class AutoMapperConfig
{
public static MapperConfiguration MapperConfiguration { get; set; }
public static void Configure()
{
MapperConfiguration = new MapperConfiguration(cfg => {
cfg.AddProfile<Out>();
cfg.CreateMap<SuperModel, SuperEntity>();
});
MapperConfiguration.AssertConfigurationIsValid();
}
}
public class Out: Profile
{
protected override void Configure()
{
CreateMap<Model1, Entity1>();
CreateMap<Model2, Entity2>()
.ForMember(dest => dest.NickName, opt => opt.Ignore());
CreateMap<Model1, Entity2>()
.ForMember(dest => dest.Married, opt => opt.Ignore())
.ForMember(dest => dest.Children, opt => opt.Ignore())
.ForMember(dest => dest.HasPet, opt => opt.Ignore());
CreateMap<SuperModel, SuperEntity>()
.ForMember(dest => dest.Entity1, opt => opt.MapFrom(src => src.Model1))
.ForMember(dest => dest.Entity2, opt => opt.MapFrom(src => src.Model2));
}
}
當我需要被轉換的對象,我下一步(在這一點上我已經_superModel
初始化,並用數據填充):
SuperEntity _superEntity = new SuperEntity();
AutoMapperConfig.MapperConfiguration.CreateMapper().Map<SuperModel, SuperEntity>(_superModel, _superEntity);
所以,我映射到Model1
Entity1
(女巫是罰款),也Model2
到Entity2
(女巫也很好,除了ID屬性,它被忽略) 。
主要對象SuperModel
和SuperEntity
也被映射,並且似乎工作正常。
問題發生在我將Model1
映射到Entity2
時,得到NickName
(認爲其餘屬性被忽略)。一些如何總是null
!
任何想法?
你怎麼樣的地圖? –
@ArturoMenchaca你是對的,我忘了提及它。請再次看到問題 - 只需編輯它。 – neoselcev