将展平对象的属性映射为集合

Mapping flattened object's properties as collection

我已将对象列表扁平化,如下所示:

//SOURCE OBJECT
public class SourceObject
{
    public string Code { get; set; }
    public string Name { get; set; }
    public string ImageUri1 { get; set; }
    public string ImageUri2 { get; set; }
    public string ImageUri3 { get; set; }
    // etc...
}

//TARGET OBJECT
public class TargetObject
{
    public string Code { get; set; }
    public string Name { get; set; }

    public List<TargetObjectImage> Images {get;set;}
}

public class TargetObjectImage
{
    public string Name { get; set; }
    public string ImageUri { get; set; }
}

我需要将 SourceObject 的一些属性映射到嵌套集合 TargetObjectImage 以及 TargetObject 的导航 属性。

所以实际上,我想调用“UNPIVOT”操作。 此外,源数据结构并不总是必须存储所有图像,在这种情况下 ImageUri... 属性 将被清空,不应添加到嵌套集合中。

public class SourceObjectProfile : Profile
{
    public SourceObjectProfile()
    {
        var map = CreateMap<SourceObject, TargetObject>()
        .ForMember(o => o.Name, o => o.MapFrom(m => m.Name))
        .ForMember(o => o.Code, o => o.MapFrom(m => m.Code))
    }
}

我正在使用 AutoMapper。我可以要求任何提示吗?

这是工作代码:

    public class CustomResolver : IValueResolver<SourceObject, TargetObject, List<TargetObjectImage>>
    {
        public List<TargetObjectImage> Resolve(SourceObject source, TargetObject destination, List<TargetObjectImage> destMember, ResolutionContext context)
        {
            return new List<TargetObjectImage>
                        {
                            new TargetObjectImage
                            {
                                Uri = source.ImageUri1
                            },
                            new TargetObjectImage
                            {
                                Uri = source.ImageUri2
                            },
                            new TargetObjectImage
                            {
                                Uri = source.ImageUri3
                            },
                        };     
        }
    }

    public class SourceObjectProfile : Profile
    {
        public SourceObjectProfile()
        {
            var map = CreateMap<SourceObject, TargetObject>()
            .ForMember(o => o.Name, o => o.MapFrom(m => m.Name))
            .ForMember(o => o.Code, o => o.MapFrom(m => m.Code))
            .ForMember(o => o.Images, o => o.MapFrom(new CustomResolver()));
        }
    }