5

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

4

2 回答 2

4

映射

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);
于 2013-01-21T15:15:51.267 回答
0

所以 Image 和 ImageDTO 是 1:1 的关系。这很容易通过 AutoMappper 映射

Mapper.CreateMap<Image, ImageDTO>();

映射器.CreateMap(); 最后一个 Student 和 StudentDTO,他们有包含列表。

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

有时,如果您尝试这样做对性能不利。谢谢

于 2015-10-10T03:32:10.223 回答