Many-to-many to DTOs using Automapper

廉价感情. 提交于 2019-12-05 00:01:03

问题


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 the 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 map from Student to StudentDTO and from Image to ImageDTO using Automapper?


回答1:


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));

Usage

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



回答2:


So Image and ImageDTO is relationship 1:1.That's easy mapping by AutoMappper

Mapper.CreateMap<Image, ImageDTO>();

Mapper.CreateMap(); The last Student and StudentDTO, they have include list.

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

Sometime if you try that it not good for performance. Thanks



来源:https://stackoverflow.com/questions/14441321/many-to-many-to-dtos-using-automapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!