[英]Automapper: mapping between different types
Assuming I have a class structure like假设我有一个 class 结构,如
public class Entity
{
public List<EntityChild> Children { get; set; }
}
public class EntityChild
{
public int Id { get; set; }
public string Name { get; set; }
}
and I want to map Entity
using AutoMapper to a class EntityDto
and reverse.我想使用 AutoMapper 将 map Entity
转换为 class EntityDto
并反转。
public class EntityDto
{
public List<int> EntityChildrenIds { get; set; }
}
I don't have any clue how to configure AutoMapper to map this properly in both directions.我不知道如何在两个方向上正确地将 AutoMapper 配置为 map。 I know my Name property will be null when mapping from EntityDto
to Entity
but this would not be a problem.我知道从EntityDto
映射到Entity
时,我的 Name 属性将为 null ,但这不会有问题。
For mapping both ways this configuration works for me:为了映射两种方式,此配置对我有用:
var mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Entity, EntityDto>()
.ForMember(dest => dest.EntityChildrenIds, opt => opt.MapFrom(src => src.Children))
.ReverseMap();
cfg.CreateMap<EntityChild, int>().ConvertUsing(child => child.Id);
cfg.CreateMap<int, EntityChild>().ConvertUsing(id => new EntityChild
{
Id = id
});
});
Since the properties have different names we need to configure that mapping.由于属性具有不同的名称,我们需要配置该映射。
Then just add general mappings from EntityChild
to int
and back again and we're done.然后只需添加从EntityChild
到int
的通用映射并再次返回,我们就完成了。
if .ReverseMap()
, as mentioned by @knoop, didn't work maybe you should map it manually:如果.ReverseMap()
,正如@knoop 提到的那样,不起作用,也许你应该手动 map :
CreateMap<Entity, EntityDto>(MemberList.None)
.ForMember(dest => dest.EntityChildrenIds, opts => opts.MapFrom(src => MapChildrenIds(src.Children)));
CreateMap<EntityDto, Entity>(MemberList.None)
.ForMember(dest => dest.Children, opts => opts.MapFrom(src => MapChildren(src.EntityChildrenIds)));
private List<EntityChild> MapChildren(List<int> entityChildrenIds)
{
var listEntityChild = new List<EntityChild>();
foreach (var childId in entityChildrenIds)
listEntityChild.Add(new EntityChild { Id = childId });
return listEntityChild;
}
private List<int> MapChildrenIds(List<EntityChild> children)
{
return children.Select(x => x.Id).ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.