0

我收到了一个很好的实现表单,映射了嵌套子元素的键 (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;
}

这是项目DTO:

[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 的 Screenshots 属性中。

任何帮助是极大的赞赏。

谢谢。

4

1 回答 1

0

您可以定义 and 之间的映射Screenshot和and 之间的KeyValuePair<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
于 2012-08-22T11:16:21.313 回答