【发布时间】:2016-04-19 04:32:40
【问题描述】:
在让 automapper 工作 (previous question) 之后,我正在为另一个问题苦苦挣扎(把它带到另一个问题上,所以第一个问题不会太复杂)...
我有下一堂课:
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(witch 很好),还将Model2 映射到Entity2(witch 也很好,除了 Id 属性,它被忽略了)。
主要对象SuperModel 和SuperEntity 也被映射,并且似乎工作正常。
当我将Model1 映射到Entity2 以获取NickName 时,问题发生了(认为其余属性被忽略)。一些方式总是null!
有什么想法吗?
【问题讨论】:
-
你的地图做得怎么样?
-
@ArturoMenchaca 你说得对,我忘了提。请再次查看问题 - 刚刚对其进行了编辑。
标签: c# .net automapper