将模型映射到dto并仅“包含"对< id,string>子元素的 [英] Mapping a model into a dto and 'include' only the pair <id,string> of child element
问题描述
我收到了一个很好的实现形式,映射了一个嵌套子代的键(ID)(请参阅此处:),但在这里我搜索了一个稍有不同的解决方案,如下所述.
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.
我有以下项目模型:
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; }
}
如您所见,每个项目都附有一些屏幕截图.在下面的函数中,我想检索一些项目,并且只检索对应屏幕快照的"ScreenshotID + ScreenshotName"对.
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;
}
这是ProjectDTO:
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; }
所以我不知道如何将"ScreenshotID + ScreenshotName"映射到我的DTO的Screenshots属性中.
So I don't know how to map "ScreenshotID + ScreenshotName" into the Screenshots property of my DTO.
非常感谢您的帮助.
谢谢.
推荐答案
您可以定义Screenshot
和KeyValuePair<int, string>
之间的映射以及Project
和ProjectDTO
之间的映射:
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>();
然后:
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
这篇关于将模型映射到dto并仅“包含"对< id,string>子元素的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!