AutoMapper 11 映射 ReadOnlyCollection 的行为 属性

AutoMapper 11 behaviors of mapping ReadOnlyCollection property

我是 AutoMapper 的新手,我想在他们的 github 上 post 这个问题,但考虑到他们的问题模板:

If you're new to AutoMapper, please ask a question on Whosebug first and come back here if the people there consider it a bug.

我必须post这里。

为了简化问题,我尽可能删除了不必要的代码。

class Rule {
    public ReadOnlyCollection<string>? Collection { get; set; }
}

var config = new MapperConfiguration(c => {
    c.CreateMap<Rule, Rule>();
});
config.AssertConfigurationIsValid();

var mapper = config.CreateMapper();

var source = new Rule {
    Collection = Array.AsReadOnly(new [] { "a", "b", "c" })
};
var destination = new Rule();

// The following line throw an exception: 
// ArgumentException: System.Collections.ObjectModel.ReadOnlyCollection`1[System.String] 
// needs to have a constructor with 0 args or only optional args.
// Validate your configuration for details.
mapper.Map(source, destination); 

并且docs说:

When calling Map with an existing readonly collection, such as IEnumerable<>, the setter will be used to replace it. If you actually have to map into that collection, you need to change its type to a writable collection, such as List<>, HashSet<>, ICollection<>, IList<> or IList. Alternatively, you can remove the setter or set UseDestinationValue.

但异常似乎告诉我 mapper 将进行深度克隆而不是 the setter will be used to replace it

AutoMapper 版本:11.0.1

对不起我的鲁莽。

其实Ruleclass不止一个ReadOnlyCollection<string>?属性:

class Rule {
    public ReadOnlyCollection<string>? CollectionA { get; set; }
    public ReadOnlyCollection<string>? CollectionB { get; set; }
}

因此,作为我的原始问题的以下代码从未初始化 CollectionB:

var source = new Rule {
    CollectionA = Array.AsReadOnly(new [] { "a", "b", "c" })
};
var destination = new Rule();

mapper.Map(source, destination); 

导致AutoMapper的null问题,解决办法是append ForAllMembers(o => o.AllowNull()) when CreateMap

var config = new MapperConfiguration(c => {
    c.CreateMap<Rule, Rule>().ForAllMembers(o => o.AllowNull());
});

抱歉,各位!!!