AutoMapper:最大图形深度

And*_*sen 1 c# automapper-3

我有以下与列表相关的实体:

国家 - >地区 - >市政 - >街

当我将Country对象映射到DTO时,AutoMapper会自动将整个图形投影到Streets,这是一个很好的默认设置.在一个特定的用例中,我想只映射根对象(Country)及其直接子对象(Regions).这些区域应该具有空的市政列表(或null).

实现此目的的一种方法是创建这样的地图:

Mapper.CreateMap<Data.Country, Dto.Country>();
Mapper.CreateMap<Data.Region, Dto.Region>()
  .ForMember(dest => dest.Municipalities, opt => opt.Ignore())
Run Code Online (Sandbox Code Playgroud)

这意味着当将Region作为根对象进行投影时,其城市列表将被忽略.解决方法是为每个可能的根对象创建单独的ConfigurationStore对象,但这会导致许多不同的ConfigurationStore.有没有办法告诉AutoMapper只映射到对象图中的某个深度?

小智 5

是的,您可以定义特定于地图的MaxDepth:

Mapper.CreateMap<Source, Destination>().MaxDepth(1);
Run Code Online (Sandbox Code Playgroud)

更多信息:https: //github.com/AutoMapper/AutoMapper/wiki

  • 如何为所有地图设置此项?像MaxDepth的默认值 (2认同)