var user = new User() { Id = 1, Age = 10, Name = , CreatedTime = DateTime.Now, ModifiedTime = DateTime.Now }; Mapper.Initialize(cfg => cfg.CreateMap<User, UserDTO>()); var userDTO = Mapper.Map<User, UserDTO>(user);
好了,看来也是支持的,我们总结来一个:AutoMapper从映射源到映射目标支持继承。讲完关于类的继承,我们来看看复杂对象,这下AutoMapper想必要有点挑战了吧。
public class Address { public string City { get; set; } public string State { get; set; } public string Country { get; set; } } public class AuthorModel { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Address Address { get; set; } }
public class AuthorDTO { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } }
static void Main(string[] args) { var author = new AuthorModel() { Id = 1, FirstName = , LastName = , Address = new Address() { City = , State = , Country = } }; Mapper.Initialize(cfg => cfg.CreateMap<AuthorModel, AuthorDTO>()); var authorDTO = Mapper.Map<AuthorModel, AuthorDTO>(author); Console.ReadKey(); }
哇喔,我说AutoMapper还能有这么智能,那还要我们程序员干嘛,在AuthorDTO中我们将Address扁平化为简单属性,所以此时利用Map不再是万能的,我们需要手动在创建映射配置时通过ForMember方法来自定义指定映射属性来源,从映射源中的Address复杂对象属性到AuthorDTO中属性上。
var author = new AuthorModel() { Id = 1, FirstName = , LastName = , Address = new Address() { City = , State = , Country = } }; Mapper.Initialize(cfg => cfg.CreateMap<AuthorModel, AuthorDTO>() .ForMember(d => d.City, o => o.MapFrom(s => s.Address.City)) .ForMember(d => d.State, o => o.MapFrom(s => s.Address.State)) .ForMember(d => d.Country, o => o.MapFrom(s => s.Address.Country)) ); var authorDTO = Mapper.Map<AuthorModel, AuthorDTO>(author);
如上所给片段代码,对于AuthorDTO中的City属性,我们指定其值来源于映射源中复杂属性Address中的City,其余同理,同时对于其他在相同层次上的属性不会进行覆盖。
默认情况下AutoMapper会将同名且不区分大小写的属性进行映射,比如对于有些属性为了节省传输流量且完全不需要用到的属性,我们压根没必要进行映射,此时AutoMapper中有Ignore方法来忽略映射,如下代码片段将忽略对属性Id的映射。
Mapper.Initialize(cfg => cfg.CreateMap<AuthorModel, AuthorDTO>() .ForMember(d => d.Id, o => o.Ignore()) );
到此我们又可以来一个总结:AutoMapper支持从映射源到映射目标的扁平化。实际上AutoMapper支持扁平化映射,但是前提是遵守AutoMapper映射约定才行,我们走一个。