0

我有以下项目模型:

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

如您所见,每个项目都附有一些屏幕截图。在下面的函数中,我想检索一些项目,并且只检索相应截图的 ID。

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 IEnumerable<int> ScreenshotID { get; set; }

所以我不知道如何在我的 DTO 中映射 ScreenshotID。

任何帮助是极大的赞赏。

谢谢。

4

1 回答 1

0

Screenshot在和之间创建一个映射int

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

和里面的映射ProjectProjectDTO使用它:

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
于 2012-08-22T06:47:47.803 回答