gpt4 book ai didi

entity-framework - 使用 Automapper 实现多对多到 DTO

转载 作者:行者123 更新时间:2023-12-03 23:38:44 24 4
gpt4 key购买 nike

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

最佳答案

映射

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

关于entity-framework - 使用 Automapper 实现多对多到 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14441321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com