升级到Automapper 3后,集合映射被破坏。*,当集合被懒惰地初始化时

时间:2013-12-16 10:39:16

标签: c# automapper

考虑这些课程:

class Master
{
    public int Id { get; set; }
    public ObservableCollection<Detail> Details
    {
        get
        {
            return details ?? (details = new ObservableCollection<Detail>());
        }
    }
    private ObservableCollection<Detail> details;
}

class Detail
{
    public int Id { get; set; }
    public int MasterId { get; set; }
}

...以及一些使用Automapper 3.0或更高版本的代码:

        Mapper.CreateMap<Master, Master>();
        Mapper.CreateMap<Detail, Detail>();
        Mapper.AssertConfigurationIsValid();

        var original = new Master
        {
            Id = 1,
            Details = 
            {
                new Detail { Id = 1, MasterId = 1 },
                new Detail { Id = 2, MasterId = 1 },
                new Detail { Id = 3, MasterId = 1 },
            }
        };

        var copy = Mapper.Map<Master>(original);

        Console.WriteLine(copy.Details.Count); // outputs 0

现在,让我们改变Master定义(用read-write替换只读,懒惰初始化的集合属性):

class Master
{
    public int Id { get; set; }
    public ObservableCollection<Detail> Details { get; set; }
}

...和示例代码(现在我们应该调用集合构造函数):

        Mapper.CreateMap<Master, Master>();
        Mapper.CreateMap<Detail, Detail>();
        Mapper.AssertConfigurationIsValid();

        var original = new Master
        {
            Id = 1,
            Details = new ObservableCollection<Detail>
            {
                new Detail { Id = 1, MasterId = 1 },
                new Detail { Id = 2, MasterId = 1 },
                new Detail { Id = 3, MasterId = 1 },
            }
        };

        var copy = Mapper.Map<Master>(original);

        Console.WriteLine(copy.Details.Count); // outputs 3

在Automapper 3.0版之前,收集项已成功复制。

问题:

  • 有没有官方解释,为什么这种行为被打破?
  • 是否有任何解决方法(除了将集合更改为读/写属性,手动复制或降级到以前版本的Automapper)?

P.S。我已经问了类似的问题,但是没有回答,现在我可以发布一个代码,这会重现错误的行为。

0 个答案:

没有答案