【问题标题】:Automapper - How to map from source child object to destinationAutomapper - 如何从源子对象映射到目标
【发布时间】:2017-06-19 03:35:19
【问题描述】:

我正在尝试从源的子对象映射到目标(作为父对象)。

源模型:

public class SourceBaseResponse<T> where T : new()
{
    public string Type { get; set; }

    public string Id { get; set; }

    public T Attributes { get; set; }
}

在我的示例中,我使用 T 为 SourceAssignment 类型

 public class SourceAssignment
{
    public string Id { get; set; }

    public string Email { get; set; }

    public string EmployeeId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTimeOffset CreatedAt { get; set; }

}

目标对象

public class DestinationAssignment
{
    public string Id { get; set; }

    public string Email { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}

我想将源模型直接映射到目标。所以,我试图使用

CreateMap<SourceAssignment, DestinationAssignment>();
CreateMap<SourceBaseResponse<SourceAssignment>, DestinationAssignment>()
            .ForMember(dest => dest, opt => opt.MapFrom(src => AutoMapperConfig.Mapper.Map<DestinationAssignment>(src.Attributes)));

这不起作用,因为我在上面的行中遇到运行时错误,即“只支持类型上的顶级个人成员。”

所以,按照this thread,我尝试了以下方法

CreateMap<SourceBaseResponse<SourceAssignment>, DestinationAssignment>()
            .AfterMap((src, dst) => Mapper.Map(src.Attributes, dst));

现在,我在应该发生映射的地方遇到错误,上面写着“映射器未初始化。使用适当的配置调用初始化。如果您尝试通过容器或其他方式使用映射器实例,请确保您没有对静态 Mapper.Map 方法,如果您使用 ProjectTo 或 UseAsDataSource 扩展方法,请确保传入适当的 IConfigurationProvider 实例。”

我可以为每个属性使用 ForMember 并将其从 src.Attributes 映射到 dest(例如:src.Attribute.Id 到 dest.Id)。这可行,但我真的不想这样做,因为我的 Source 是涉及嵌套子级的复杂类(因为这是一个 Web API 响应,我无法控制它)。所以这里做了很多自定义映射

CreateMap<SourceAssignment, DestinationAssignment>();

关于如何进行的任何建议。

【问题讨论】:

  • AfterMap 表达式使用静态Mapper,因此请确保它已配置(即静态映射器具有 SourceAssignment -> DestinationAssignment 的映射)。也许您当前正在配置实例而不是静态映射器?
  • @GeorgPatscheider 是一个静态映射器。如果不是从 SourceBaseResponse 映射,我可以将其用于将 Source 自动映射到 Destination。

标签: c# automapper automapper-5


【解决方案1】:

需要解析上下文才能调用Mapper.Map(),可以通过ConstructUsing()获取解析上下文:

CreateMap<SourceChild, Destination>();
CreateMap<Source, Destination>()
    .ConstructUsing((src, ctx) => ctx.Mapper.Map<Destination>(src.SourceChild));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 2021-02-22
    • 2018-06-18
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多