Mapping a model into a dto and 'include' o

2019-08-30 04:07发布

问题:

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

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

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

Any help is greatly appreciated.

Thanks.

回答1:

Create a mapping between Screenshot and int:

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

and inside the mapping between Project and ProjectDTO use it:

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

And when you want to map:

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