【问题标题】:Automapper nested Collections without setter没有设置器的自动映射器嵌套集合
【发布时间】:2019-04-10 23:56:13
【问题描述】:

我在 LinqPad(C# 程序)上运行了这段代码 sn-p,其中已经包含 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 添加任何元素。

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

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

【问题讨论】:

  • cfg.CreateMap&lt;Top, TopDto&gt;().ReverseMap().ForMember(d=&gt;d.Nicks, o=&gt; { o.MapFrom(s=&gt;s.Nicks); o.UseDestinationValue(); }); 详见this
  • 嗨@LucianBargaoanu,关键是你的o.UseDestinationValue(); 谢谢。你能把它写成接受它的答案吗?问候。
  • 没关系。但是,如果您愿意,请随时写一个更详细的答案。
  • @LucianBargaoanu 我有一个问题。有没有办法在全球范围内定义这个。我正在更新我的映射器,似乎私有设置器在 v6 之后没有被映射。我在整个项目中都有私人设置器,似乎很难单独设置它。

标签: c# automapper automapper-6


【解决方案1】:

感谢@LucianBargaoanu(在 cmets 中),现在通过这种方式解决了这个问题:

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; }
}

问候。

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2021-01-20
    • 2014-09-26
    • 1970-01-01
    相关资源
    最近更新 更多