无嵌入器的Automapper嵌套集合

时间:2017-10-31 14:28:40

标签: c# automapper automapper-6

我在LinqPad(C#程序)上运行了此代码段,其中包含Automapper Nuget包6.1.1:

void Main()
{
    Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Top, TopDto>().ReverseMap();
            });

    Mapper.AssertConfigurationIsValid();

    var source = new TopDto
    {
        Id = 1,
        Name = "Charlie",
        Nicks = new List<string> { "Fernandez", "Others" }
    };


    var destination = Mapper.Map<Top>(source);

    destination.Dump();

}

// Define other methods and classes here
public class Top
{
    public Top()
    {
        Nicks = new List<string>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> Nicks { get; }
}

public class TopDto
{
    public TopDto()
    {
        Nicks = new List<string>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> Nicks { get; set; }
}

正如您所看到的,我们在设置嵌套Collection时遇到了问题(根本没有Setter)。从理论上讲,它应该运行良好,但它不会在Collection中添加任何元素。

如果我们更改集合属性添加公共setter,那么一切都很好。

如何在不添加公共设置器或设置器的情况下获取嵌套集合?

1 个答案:

答案 0 :(得分:3)

感谢@LucianBargaoanu(在评论中)现在以这种方式解决了这个问题:

void Main()
{
    Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Top, TopDto>().ReverseMap()
                    .ForMember(d => d.Nicks, o=> 
                                                { 
                                                    o.MapFrom(s => s.Nicks);
                                                    o.UseDestinationValue(); 
                                                });
            });

    Mapper.AssertConfigurationIsValid();

    var source = new TopDto(new List<string> { "Fernandez", "Others" })
    {
        Id = 1,
        Name = "Charlie"
    };


    var destination = Mapper.Map<Top>(source);

    destination.Dump();

}

// Define other methods and classes here
public class Top
{
    public Top()
    {
        Nicks = new List<string>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> Nicks { get; }
}

public class TopDto
{
    public TopDto(List<string> nicks)
    {
        Nicks = nicks;
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<string> Nicks { get; private set; }
}

问候。