自动映射配置以将对象映射到数组

时间:2018-06-14 15:48:48

标签: c# .net-core automapper

我在.net核心项目中使用了automapper 7.0.0。我有以下repro,它描述了我将用另一种类型的集合转换为dto的用例,该dto描述了父集合中的父节点和每个子节点:

using System.Linq;
using AutoMapper;

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        this.CreateMap<Foo, BarDto[]>()
            .ConvertUsing((src, dst) =>
            {
                return src.Bars.Select(x =>
                        new BarDto
                        {
                            MyPropA = x.MyPropA,
                            MyPropB = x.MyPropB,
                            PropA = src.PropA,
                            PropB = src.PropB
                        })
                    .ToArray();
            });
    }
}

public class Bar
{
    public string MyPropA { get; set; }
    public string MyPropB { get; set; }
}

public class BarDto
{
    public string MyPropA { get; set; }
    public string MyPropB { get; set; }
    public string PropA { get; set; }
    public string PropB { get; set; }
}

public class Foo
{
    public Bar[] Bars { get; set; }
    public string PropA { get; set; }
    public string PropB { get; set; }
}

internal class Program
{
    private static void Main(string[] args)
    {
        var config = new MapperConfiguration(cfg => cfg.AddProfiles(typeof(AutoMapperProfile).Assembly));
        config.AssertConfigurationIsValid();
        IMapper mapper = new Mapper(config);

        Foo foo = new Foo
        {
            PropA = "PropA Value",
            PropB = "PropB Value",
            Bars = new[]
            {
                new Bar {MyPropA = "Bar 1 MyPropA", MyPropB = "Bar 1 MyPropB"},
                new Bar {MyPropA = "Bar 2 MyPropA", MyPropB = "Bar 2 MyPropB"}
            }
        };

        BarDto[] barDtos = mapper.Map<Foo, BarDto[]>(foo);
    }
}

然而这感觉不对。它在设计的早期,我有机会改变领域或类型。是否有一个我可以遵守的约定,以便于将这两种类型自动映射到dto对象中?

0 个答案:

没有答案