Here’s a quick demo of Automapper a library to assist with mapping object items between objects.
using System; using AutoMapper; namespace CsharpAutoMapperDemo { class CsharpAutoMapperExample { static void Main() { Mapper.CreateMap<User, Person>(); var userWithAutoMap = new User() { FirstName = "FirstName", LastName = "LastName", UserId = "My user id", Password = "My password", EmailAddress = "My email", }; var personWithAutoMap = Mapper.Map<User, Person>(userWithAutoMap); Console.WriteLine(personWithAutoMap.FirstName); Console.WriteLine(personWithAutoMap.LastName); Console.WriteLine(personWithAutoMap.EmailAddress); Console.WriteLine(); Mapper.Reset(); Mapper.CreateMap<User, Person>() .ForMember(x => x.EmailAddress, y => y.MapFrom(src => src.FirstName + "" + src.LastName + "@email.com")); var userWithManualMap = new User() { FirstName = "FirstName", LastName = "LastName", UserId = "My user id", Password = "My password", EmailAddress = "My email", }; var personWithManualMap = Mapper.Map<User, Person>(userWithManualMap); Console.WriteLine(personWithManualMap.FirstName); Console.WriteLine(personWithManualMap.LastName); Console.WriteLine(personWithManualMap.EmailAddress); Console.ReadKey(); } } }
The mapping classes:
namespace CsharpAutoMapperDemo { class User { public string FirstName { get; set; } public string LastName { get; set; } public string UserId { get; set; } public string Password { get; set; } public string EmailAddress { get; set; } } } namespace CsharpAutoMapperDemo { class Person { public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string HomeAddress { get; set; } public string BuildingLocation { get; set; } } }
The resultant output:
FirstName
LastName
My email
FirstName
LastName
[email protected]