Many-to-many for DTO with Automapper

If I have a many-to-many relationship defined in EF:

public class StudentImage { public int StudentId { get; set; } public int ImageId { get; set; } public int Order { get; set; } public virtual Student Student { get; set; } public virtual Image Image { get; set; } } public class Student { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<StudentImage> Images { get; set; } } public class Image { public int Id { get; set; } public string Filename { get; set; } public virtual ICollection<StudentImage> Students { get; set; } } 

And DTO's:

  public class ImageDTO { public int Id { get; set; } public string Filename { get; set; } public int Order { get; set; } } public class StudentIDO { public int Id { get; set; } public string Name { get; set; } public ICollection<ImageDTO> Images { get; set; } } 

How could I display from Student to StudentDTO and from Image to ImageDTO using Automapper?

+4
source share
2 answers

Mappings

 Mapper.CreateMap<Student, StudentIDO>(); Mapper.CreateMap<StudentImage, ImageDTO>() .ForMember(d => d.Id, opt => opt.MapFrom(s => s.ImageId)) .ForMember(d => d.Filename, opt => opt.MapFrom(s => s.Image.Filename)); Mapper.CreateMap<StudentIDO, Student>() .AfterMap((s, d) => { foreach (var studentImage in d.Images) studentImage.StudentId = s.Id; }); Mapper.CreateMap<ImageDTO, StudentImage>() .ForMember(d => d.ImageId, opt => opt.MapFrom(s => s.Id)); 

Using

 var studentDTO = Mapper.Map<StudentIDO>(student); var student = Mapper.Map<Student>(studentDTO); 
+3
source

So, Image and ImageDTO are 1: 1 ratios. This is a simple mapping using AutoMappper

 Mapper.CreateMap<Image, ImageDTO>(); 

Mapper.CreateMap (); Last Student and StudentDTO, they have a list.

 Mapper.CreateMap<Student,StudentDTO> .ForMember(s => s.Images, opt=>opt.MapFrom(p=>p.Images)); 

Someday, if you try, this is not good for performance. Thanks

0
source

All Articles