繁体   English   中英

Automapper - 如何从源子对象映射到目标

[英]Automapper - How to map from source child object to destination

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

来源模型:

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

    public string Id { get; set; }

    public T Attributes { get; set; }
}

对于我的例子,我使用的是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; }
}

我想将Source Model直接映射到Destination。 所以,我试图使用

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

这不起作用,因为我在上面的行中出现“运行时错误”,“仅对类型的顶级个人成员支持成员的自定义配置”。

所以,根据这个帖子,我尝试了以下内容

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

现在,我收到错误,其中应该发生映射,其中显示“Mapper未初始化。使用适当的配置调用Initialize。如果您尝试通过容器或其他方式使用映射器实例,请确保您没有对静态Mapper的任何调用。映射方法,如果您正在使用ProjectTo或UseAsDataSource扩展方法,请确保传入适当的IConfigurationProvider实例。“

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

CreateMap<SourceAssignment, DestinationAssignment>();

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

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

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

暂无
暂无

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

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