如何使用AutoMapper映射嵌套对象?

问题描述 投票:0回答:1

假设我们有这个实体和相应的Dto:

public class MyEntity
{
    public string Name {get; set;}
}

public class MyEntityDto
{
    public string Name {get;set;}
}

这个Aggregate和对应的Dto:

public class MyAgg
{
    public string SomeProp {get;set;}
    public MyEntity Entity {get;set;}
}

public class MyAggDto
{
    public string SomeProp {get;set;}
    public AggDataDto Data {get;set;}
    
    public class AggDataDto
    {
        public MyEntityDto Entity {get;set;}
    }
}

这是映射配置文件:

public class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<MyEntity, MyEntityDto>();
        CreateMap<MyAgg, MyAggDto>()
            .ForMember(dest => dest.Data, opt => opt.MapFrom(src => {
                return new MyAggDto.AggDataDto
                {
                    /*
                        Can I inject and use IMapper here to get MyEntityDto from src.Entity ?
                        Should I create the Dto with new MyEntityDto(...) ?
                        Any other approach ?
                    */
                    Entity = ...
                }
            }));
    }
}

如何映射嵌套对象?

c# automapper
1个回答
0
投票
  1. 您应该创建从

    MyEntity
    MyAggDto.AggDataDto
    的映射规则。

  2. 对于从

    MyAgg
    MyAggDto
    的映射规则,将源的
    Entity
    成员映射到目标的
    Data
    成员。

public class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<MyEntity, MyEntityDto>();
        
        CreateMap<MyEntity, MyAggDto.AggDataDto>()
            .ForMember(dest => dest.Entity, opt => opt.MapFrom(src => src));
        
        CreateMap<MyAgg, MyAggDto>()
            .ForMember(dest => dest.Data, opt => opt.MapFrom(src => src.Entity));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.