映射模型转换为DTO和“包括”只有子元素的关键(Mapping a model into a dto

2019-11-01 01:01发布

我有以下的项目模型:

public class Project
{
    [Key]
    public int      ProjectID       { get; set; }
    public string   Name            { get; set; }
    public string   Description     { get; set; }     
    public virtual  ICollection<Screenshot> Screenshots { get; set; }   
}

我有以下截图模式:

public class Screenshot
{
    [Key]
    public int    ScreenshotID { get; set; }
    public string ScreenshotName { get; set; }
    public byte[] ScreenshotContent { get; set; }
    public string ScreenshotContentType { get; set; }
}

正如你所看到的,每个项目都附加了一些截图。 在下面的功能,我想找回一些项目和相应的截图只有ID。

public SearchResultDTO<ProjectDTO> GetProjects(SearchParametersProjectDTO dto)
{
    ...
    var resultDTO = new SearchResultDTO<ProjectDTO>
    {
        Entities = Mapper.Map<IEnumerable<Project>, IEnumerable<ProjectDTO>>(projects.ToList()),
        TotalItems = projects.Count()
    };
    return resultDTO;
}

这里是ProjectDTO:

[DataContract]
public class ProjectDTO : BaseDTO<ProjectDTO, Project>
{
    [DataMember]
    public int ProjectID { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Description { get; set; }

    [DataMember]
    public IEnumerable<int> ScreenshotID { get; set; }

所以我不知道如何在我的DTO映射ScreenshotID。

任何帮助是极大的赞赏。

谢谢。

Answer 1:

创建之间的映射Screenshotint

Mapper
    .CreateMap<Screenshot, int>()
    .ConvertUsing(s => s.ScreenshotID);

之间的映射内部ProjectProjectDTO使用它:

Mapper
    .CreateMap<Project, ProjectDTO>()
    .ForMember(
        dest => dest.ScreenshotID,
        opt => opt.MapFrom(src => src.Screenshots)
    );

而当你要映射:

var project = new Project
{
    Screenshots = new[]
    {
        new Screenshot { ScreenshotID = 1 },
        new Screenshot { ScreenshotID = 2 },
        new Screenshot { ScreenshotID = 3 },
    }
};

var projectDto = Mapper.Map<Project, ProjectDTO>(project);

// at this stage the projectDto.ScreenshotID collection will contain 
// the necessary information


文章来源: Mapping a model into a dto and 'include' only the key of child element