Mapping a model into a dto and 'include' o

2019-09-01 19:33发布

问题:

I received a nice implementation form mapping the key (ID) of a nested child (see here: Mapping a model into a dto and 'include' only the key of child element) but here I search for a slightly different solution as explained below.

I have the following Project model:

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

As you can see, each project have some screenshots attached. In the following function, I would like to retrieve some projects and only the pair ScreenshotID + ScreenshotName 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;
}

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 Dictionary<int, string> Screenshots { get; set; }

So I don't know how to map "ScreenshotID + ScreenshotName" into the Screenshots property of my DTO.

Any help is greatly appreciated.

Thanks.

回答1:

You could define a mapping between Screenshot and KeyValuePair<int, string> and a mapping between Project and ProjectDTO:

Mapper
    .CreateMap<Screenshot, KeyValuePair<int, string>>()
    .ConvertUsing(s => new KeyValuePair<int, string>(s.ScreenshotID, s.ScreenshotName));

Mapper
    .CreateMap<Project, ProjectDTO>();

and then:

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

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

// at this stage the projectDto.Screenshots dictionary will contain 
// the necessary information