public static void GenericHeterogeneousList() { var f = new Woman(); var m = new Man(); var u = new Uri("http://www.IT-Visions.de"); // Generische Liste erzeugen und befüllen var set = new Person[] { f, m }; // Mappingsdefinieren Mapper.Initialize(cfg => { cfg.CreateMap <Person, PersonDTO>() .Include <Man, ManDTO>() .Include <Woman, WomanDTO>() .ForMember(z => z.Name, map => map.MapFrom(q => q.GivenName + " " + q.Surname)) .ForMember(z => z.YearOfBirth, map => map.MapFrom(q => q.Birthday.Year)); cfg.CreateMap <Man, ManDTO>(); cfg.CreateMap <Woman, WomanDTO>(); }); //Mapper.CreateMap<System.Uri, string>().ConvertUsing<UriToStringConverter>(); // Einzelmapping zum test //string s = Mapper.Map<string>(u); var set2 = Mapper.Map <Person[], PersonDTO[]>(set); Console.WriteLine(((ManDTO)set2[0]).NumberOfCars); Console.WriteLine(((WomanDTO)set2[1]).NumberOfShoes); }
public static void Inheritance() { CUI.Headline(nameof(Inheritance)); Mapper.Initialize(cfg => { cfg.CreateMap <Person, PersonDTO>() .ForMember(z => z.Name, map => map.MapFrom(q => q.GivenName + " " + q.Surname)) .ForMember(z => z.YearOfBirth, map => map.MapFrom(q => q.Birthday.Year)); cfg.CreateMap <Man, ManDTO>() .ForMember(z => z.Name, map => map.MapFrom(q => q.GivenName + " " + q.Surname)) .ForMember(z => z.YearOfBirth, map => map.MapFrom(q => q.Birthday.Year)); cfg.CreateMap <Woman, WomanDTO>() .ForMember(z => z.Name, map => map.MapFrom(q => q.GivenName + " " + q.Surname)) .ForMember(z => z.YearOfBirth, map => map.MapFrom(q => q.Birthday.Year)); }); // or shorter using include() Mapper.Initialize(cfg => { cfg.CreateMap <Person, PersonDTO>() .Include <Man, ManDTO>() .Include <Woman, WomanDTO>() .ForMember(z => z.Name, map => map.MapFrom(q => q.GivenName + " " + q.Surname)) .ForMember(z => z.YearOfBirth, map => map.MapFrom(q => q.Birthday.Year)); cfg.CreateMap <Man, ManDTO>(); cfg.CreateMap <Woman, WomanDTO>(); }); var m = new Man() { GivenName = "John", Surname = "Doe", Birthday = new DateTime(1980, 10, 1), NumberOfCars = 40 }; PersonDTO mDTO1 = Mapper.Map <PersonDTO>(m); Console.WriteLine(mDTO1.Name + " *" + mDTO1.YearOfBirth); ManDTO mDTO1b = Mapper.Map <ManDTO>(m); Console.WriteLine(mDTO1b.Name + " *" + mDTO1b.YearOfBirth); ManDTO mDTO2 = (ManDTO)Mapper.Map(m, m.GetType(), typeof(ManDTO)); Console.WriteLine(mDTO2.Name + " *" + mDTO2.YearOfBirth + " owns " + mDTO2.NumberOfCars + " cars."); ManDTO mDTO3 = Mapper.Map <ManDTO>(m); Console.WriteLine(mDTO3.Name + " *" + mDTO3.YearOfBirth + " owns " + mDTO3.NumberOfCars + " cars."); // gender transformation: man -> woman Mapper.Initialize(cfg => { cfg.CreateMap <Man, Woman>() .ForMember(z => z.NumberOfShoes, map => map.MapFrom(q => q.NumberOfCars * 10)); }); Woman f = Mapper.Map <Woman>(m); Console.WriteLine(f.GivenName + " " + f.Surname + " *" + f.Birthday + " owns " + f.NumberOfShoes + " shoes."); }