我正在尝试将不同类型的两个源集合属性转换为目标类型的相同集合属性。 在我的源类型和目标集合的项目类型之间进行转换。
问题是MapFrom
代码实际上没有设置目标属性。
我正在使用自动映射器8。
这是我的问题的一个最小例子。
来源
public class SourceWithDict
{
public List<HasLabel> Prop1 { get; } = new List<HasLabel>();
public List<HasName> Prop2 { get; } = new List<HasName>();
}
public class HasLabel
{
public string Label { get; set; }
}
public class HasName
{
public string Name { get; set; }
}
目的地
public class DestinationDict
{
public List<string> Prop1And2 { get; } = new List<string>();
}
映射
ForAllPropertyMaps(pm => pm.DestinationName != "DictWithoutUseDestinationValue",
(map, expression) => expression.UseDestinationValue());
CreateMap<HasLabel, string>()?.ConvertUsing(label => label.Label);
CreateMap<HasName, string>()?.ConvertUsing(name => name.Name);
CreateMap<SourceWithDict, DestinationDict>()
?.ForMember(dest => dest.Prop1And2, o =>
{
o.MapFrom((source, destination, member, context) =>
{
// this seems to set Prop1And2 correctly during debugging, but the mapped result is empty
destination.Prop1And2.AddRange(context.Mapper.Map<List<string>>(source.Prop1));
destination.Prop1And2.AddRange(context.Mapper.Map<List<string>>(source.Prop2));
member = destination.Prop1And2;
return destination.Prop1And2;
});
});
测试代码
[Test]
public void Mapping_merged_Properties()
{
var source = new SourceWithDict();
var hasLabel = new HasLabel() {Label = "abba"};
source.Prop1.Add(hasLabel);
var hasName = new HasName() {Name = "doch"};
source.Prop2.Add(hasName);
var mapped = Mapper.Map<DestinationDict>(source);
// this fails, because mapped.Prop1And2 remains empty
Assert.That(mapped.Prop1And2, Has.Count.EqualTo(2).And.EquivalentTo(new [] {"abba","doch"}));
}