【问题标题】:How to map from nested list to destination object with automapper?如何使用自动映射器从嵌套列表映射到目标对象?
【发布时间】:2019-04-11 13:30:55
【问题描述】:

我有一个像这样的源对象:

public class ParentDto
{
    public List<EntityDto> EntityDtos { get; set; }
    // some other stuff...
}

还有一个像这样的目标对象:

public class SomeModel
{
    [Key]
    public Guid Id { get; set; }
    public Entity Entity { get; set; }
}

在我的应用程序的不同部分,我已经使用配置文件将我的 EntityDto 映射到我的实体:

CreateMap<EntityDto, Entity>()
            .ForMember(dest => dest.Member,
                opt => opt.MapFrom(src => DoSomeStuff(src.AnotherMember)))
            .ForMember(dest => dest.YetAnotherMember,
                opt => opt.MapFrom(src => DoSomeOtherStuff(src.Whatever)));

是否可以重复使用此映射来映射我的父对象 Dto,其中包括 entityDtos 列表?

CreateMap<ParentDto, SomeModel>()
            .ForMember(dest => dest.Id,
                opt => opt.Ignore())

            // some more stuff...

            // This is where I am struggling!
            .ForMember(dest => dest. Entity,
                opt => opt.MapFrom(src => src.EntityDtos[0]));

我将如何解决我已经有一个 EntityDto 到 Entity 的映射以及我必须处理该列表的事实?

【问题讨论】:

    标签: entity-framework asp.net-core automapper dto


    【解决方案1】:

    一个与另一个无关。您定义的映射是根据输入其中的对象的类型和/或指定的泛型类型参数来使用的。换句话说,像_mapper.Map&lt;SomeModel&gt;(parentDto) 这样的东西会使用CreateMap&lt;ParentDto, SomeModel&gt; 定义,而_mapper.Map&lt;Entity&gt;(entityDto) 会使用CreateMap&lt;EntityDto, Entity&gt; 定义。

    现在,当 AutoMapper 开始映射集合属性时,默认情况下它将使用 EntityDTO->Entity 映射的定义,但如果您通过 MapFrom 指定自定义映射,例如,则优先。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多