让自动映射器工作后(上一个问题 https://stackoverflow.com/questions/36602430/automapper-complex-types-mapping-exception),我正在解决另一个问题(把它带到另一个问题,所以第一个问题不会太复杂)......
我还有下一堂课:
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
to Entity1
(女巫很好),还有Model2
to Entity2
(witch 也很好,除了 Id 属性,该属性被忽略)。
主要对象SuperModel
and SuperEntity
也被映射了,并且似乎工作得很好。
当我映射时出现问题Model1
to Entity2
,得到NickName
(认为其余属性被忽略)。总是如此null
!
有任何想法吗?