Problema de mesclagem de objetos do Automapper
Depois de fazer o automapper funcionar (pergunta anterior), Estou lutando com outro problema (levou para outra pergunta, para que a primeira não fosse muito complicada) ...
Eu tenho próximas aulas:
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; }
}
Esses objetos são esquematicamente semelhantes aos meus objetos originais, exceto o nome e a complexidade.
E a classe de configuração do AutoMapper (chamada de 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));
}
}
Quando eu preciso que o objeto seja convertido, eu faço a seguir (neste momento eu tenho_superModel
inicializado e preenchido com dados):
SuperEntity _superEntity = new SuperEntity();
AutoMapperConfig.MapperConfiguration.CreateMapper().Map<SuperModel, SuperEntity>(_superModel, _superEntity);
Então eu mapeioModel1
paraEntity1
(bruxa está bem), e tambémModel2
paraEntity2
(o que também é bom, exceto a propriedade Id, que é ignorada).
Objetos principaisSuperModel
eSuperEntity
também são mapeados e parecem funcionar bem.
O problema acontece quando mapeioModel1
paraEntity2
, para obter oNickName
(o restante das propriedades é ignorado). De alguma forma, é semprenull
!
Alguma ideia?