AutoMapper - 如何在映射中利用集合索引

3
我可以帮您翻译成中文。需要将一个Dto映射到一个实体,并将Dto的数组索引存储到实体的属性中。例如(伪代码):
class Dto {}

class Entity{ int Index; }

// perform mapping from collection of Dto, to collection of Entity
Map<Entity>(new Dto[]{ new Dto(), new Dto(), new Dto() };

// maps to
Entity[]{
  Entity{ Index = 0 },
  Entity{ Index = 1 },
  Entity{ Index = 2 }
}

当然,我可以手动完成这个任务,但是我已经在我的架构中使用了AutoMapper,所以为其配置映射是有意义的。
我找不到方法来做到这一点。我找到了这个线程:https://github.com/AutoMapper/AutoMapper/issues/1238,它提到了使用解析器,但是,由于解析器不再具有访问解析层次结构/堆栈的权限,我认为这可能是为了性能原因而进行的更改,因为上面的评论是这样写的。
对我来说,我应该能够轻松地访问“root”源对象(传递给Map<>(source)方法的对象/集合),并且拥有这样的访问权限将使其变得微不足道,但是我找不到它。
有什么建议吗?
谢谢,

您可以始终在ResolutionContext中明确传递您所需的内容。 - undefined
1个回答

1

以下是使用AfterMap实现的方法:

Mapper.CreateMap<SourceDto, Destination>()
    .AfterMap((_, dest) => 
    {
        int id = 0;
        foreach (var entity in dest.Entities)
        {
            entity.Index = id++;
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接