Created
December 21, 2017 13:49
-
-
Save Asc0tt/409473b2716c93bf39026694e899592a to your computer and use it in GitHub Desktop.
mapping example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ConsoleApplication1 | |
{ | |
public class Program | |
{ | |
public class MappingProfile : Profile | |
{ | |
public MappingProfile() | |
{ | |
CreateMap<MainViewModel, MainEntity>() | |
.ForMember(dst => dst.SubEntities1, opt => opt.MapFrom(src => src.SubViewModels1)) | |
.ForMember(dst => dst.SubEntities2, opt => opt.MapFrom(src => src.SubViewModels2)) | |
.ReverseMap(); | |
CreateMap<SubViewModel1, SubEntity1>().ReverseMap(); | |
CreateMap<SubViewModel2, SubEntity2>().ReverseMap(); | |
} | |
} | |
class MainViewModel | |
{ | |
public ICollection<SubViewModel1> SubViewModels1 { get; set; } | |
public ICollection<SubViewModel2> SubViewModels2 { get; set; } | |
} | |
class SubViewModel1 | |
{ | |
} | |
class SubViewModel2 | |
{ | |
} | |
class MainEntity | |
{ | |
public List<SubEntity1> SubEntities1 { get; set; } | |
public List<SubEntity2> SubEntities2 { get; set; } | |
} | |
class SubEntity1 | |
{ | |
} | |
class SubEntity2 | |
{ | |
} | |
public static void Main(string[] args) | |
{ | |
var clientConfiguration = new MapperConfiguration( | |
cfg => | |
{ | |
cfg.AddProfile(new MappingProfile()); | |
}); | |
var mapper = clientConfiguration.CreateMapper(); | |
var result = mapper.Map<MainEntity>(new MainViewModel | |
{ | |
SubViewModels1 = new List<SubViewModel1> {new SubViewModel1()}, | |
SubViewModels2 = new List<SubViewModel2> {new SubViewModel2()} | |
}); | |
Console.WriteLine($"Count: {result.SubEntities1.Count + result.SubEntities2.Count}"); | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment