越来越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