[英]Automapper Sub Property Mapping
I have a situation where I need to map a sub-collection of items within an object to a collection of items in another object.我有一种情况,我需要将一个对象中的项目子集合映射到另一个对象中的项目集合。 I am essentially trying to flatten the object for use by a consuming system.我本质上是试图将对象展平以供消费系统使用。
Given the following entity classes:给定以下实体类:
public class PersonEntity
{
public int Id { get; set; }
public virtual ICollection<OutcomeEntity> Outcomes { get; set; }
}
public class OutcomeEntity
{
public int Id { get; set; }
public bool Outcome { get; set; }
public virtual ICollection<GradeEntity> Grades { get; set; }
public PersonEntity Person { get; set; }
}
public class GradeEntity
{
public int Id { get; set; }
public string Grade { get; set; }
public string MarkersComment { get; set; }
public OutcomeEntity Outcome { get; set; }
}
I need to map the OutcomeEntity and GradeEntity to the following flattened structure where there can be many outcomes, containing many different grades:我需要将 OutcomeEntity 和 GradeEntity 映射到以下扁平结构,其中可以有许多结果,包含许多不同的等级:
public class PersonDTO
{
public int PersonId { get; set; }
public virtual ICollection<GradeDTO> Grades { get; set; }
}
public class GradeDTO
{
public int OutcomeId { get; set; }
public int GradeId { get; set; }
public string Grade { get; set; }
public string MarkersComment { get; set; }
}
Basically, for every Outcome in the collection, I want to iterate over the grades within it and create a new object (GradeDTO).基本上,对于集合中的每个结果,我想遍历其中的成绩并创建一个新对象 (GradeDTO)。
I have attempted to create a basic map, but I simply cannot get my head around the sub-properties.我试图创建一个基本地图,但我根本无法理解子属性。
To create one collection from many you can use SelectMany
extension method.要从多个集合中创建一个集合,您可以使用SelectMany
扩展方法。 With this method and the following configuration AutoMapper will create PersonDto
from PersonEntity
.使用此方法和以下配置 AutoMapper 将从PersonDto
创建PersonEntity
。
Mapper.Initialize(cfg =>
{
cfg.CreateMap<GradeEntity, GradeDTO>()
.ForMember(dto => dto.GradeId, x => x.MapFrom(g => g.Id))
.ForMember(dto => dto.OutcomeId, x => x.MapFrom(g => g.Outcome.Id));
cfg.CreateMap<PersonEntity, PersonDTO>()
.ForMember(dto => dto.PersonId, x => x.MapFrom(p => p.Id))
.ForMember(dto => dto.Grades, x => x.MapFrom(p => p.Outcomes.SelectMany(o => o.Grades)));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.