使用Automapper对DTO进行多对多操作

时间:2013-01-21 14:59:14

标签: entity-framework many-to-many automapper dto

如果我在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; }
}

和DTO:

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

我如何使用Automapper从Student映射到StudentDTO以及从Image映射到ImageDTO?

2 个答案:

答案 0 :(得分:3)

映射

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

用法

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

答案 1 :(得分:0)

所以Image和ImageDTO是关系1:1。通过AutoMappper轻松映射

Mapper.CreateMap<Image, ImageDTO>();

Mapper.CreateMap(); 最后一个学生和学生DTO,他们有列表。

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

有时如果你尝试它对性能不利。 感谢