将模型映射到dto并仅

将模型映射到dto并仅

本文介绍了将模型映射到dto并仅“包含"子元素的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下项目模型:

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

我有以下屏幕截图模型:

And I have the following Screenshot model:

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.

As you can see, each project have some screenshots attached. In the following function, I would like to retrieve some projects and only the ID of the corresponding screenshots.

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:

Here is the 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.

So I don't know how to map ScreenshotID in my DTO.

非常感谢您的帮助.

谢谢.

推荐答案

Screenshotint之间创建映射:

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

,并在ProjectProjectDTO之间的映射中使用它:

and inside the mapping between Project and ProjectDTO use it:

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

这篇关于将模型映射到dto并仅“包含"子元素的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:23