简体   繁体   English

自动映射和映射复杂集合

[英]Automapper and mapping complex collections

Hi I have a question about automapper, thing is I have a model that has nested collection of other models, and models in that collection also has a collection of models something like (DB model): 嗨,我有一个关于自动映射器的问题,问题是我有一个嵌套了其他模型集合的模型,并且该集合中的模型也有一些模型集合(例如DB模型):

public class Cabin 
{
    public uint Id { get; set; }
    public string Name { get; set; }        
    public Rack[] Racks { get; set; }
}

public class Rack
{
    public uint Id { get; set; }
    public string RackName { get; set; }
    public IPAddress IpAddress { get; set; }
    public int Port { get; set; }
    public Module[] Modules { get; set; }
}

public class Module
{
    public uint Id { get; set; }
    public string ModuleName { get; set; }
}

Well from Dto side I have something like: 从Dto方面来看,我有类似以下内容:

public class CabinDto 
{
    public uint Id { get; set; }
    public string Name { get; set; }
    public RackDto[] Racks { get; set; }
}

public class RackDto
{
    public uint Id { get; set; }
    public string Name { get; set; }
    public ModuleDto[] Modules{ get; set; }
}

public class ModuleDto
{
    public string Name { get; set; }
}

So I want to map it all at once, but figure out a way to map a list object with different properties names. 因此,我想一次全部映射,但想出一种方法来映射具有不同属性名称的列表对象。

For main class I have: 对于主要班级,我有:

CreateMap<Db.Cabin, Dto.Cabin>()
  .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
  .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name));
  // how to map nested list

I could just add some method that assigns values and map to this method, but it does not feel right. 我可以添加一些分配值并映射到该方法的方法,但是感觉不对。 I looked in documentation and there are only examples with simple collection with same name lists. 我查看了文档,只有带有简单名称集合的示例具有相同的名称列表。

Is there a way to do it? 有办法吗?

You just need to add mapping for the type in the nested list and AutoMapper will take care of it. 您只需要在嵌套列表中为该类型添加映射,AutoMapper就会处理。

CreateMap<Db.Module, Dto.Module>();
CreateMap<Db.Rack, Dto.Rack>();

Also when the name of properties in source and origin are the same, you don't need to call the ForMember() method. 同样,如果源名称和源名称中的属性名称相同,则无需调用ForMember()方法。
So in your case you need it for the ModuleName to Name of the Module to ModuleDto mapping, and same for the Rack class, see this fiddle . 因此,在您的情况下,需要ModuleNameModule NameModuleDto映射, Rack类也需要,请参见此小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM