映射模型转换为DTO和“包括”仅在一对 子元素(Mapping a model into a

2019-11-01 01:25发布

我收到了很好的实现形式映射一个嵌套子的钥匙(ID)(在这里看到: 映射模型到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; }   
}

我有以下截图模式:

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

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

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

所以,我不知道如何“ScreenshotID + ScreenshotName”映射到我的DTO的截图性质。

任何帮助是极大的赞赏。

谢谢。

Answer 1:

你可以定义之间的映射ScreenshotKeyValuePair<int, string>之间的映射ProjectProjectDTO

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

Mapper
    .CreateMap<Project, ProjectDTO>();

接着:

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


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