我正在使用AutoMapper 6.2.2,我有一个通用方法,可以执行从一种类型到另一种类型的对象图更新。我不知道运行时的所有组合,因为mapper包含在扩展方法中,该方法使用T
作为CreateMap
类型参数。
我已完成配置,但问题是,Foo.MyBar
已更新,而不是降序并比较其子属性。如果它为null,我只希望Foo.MyBar
被完全覆盖。由于我无法专门为Foo.MyBar
进行配置,如何在我的配置中编写通用条件来满足我的需求?
我期待result.MyBar.TwoString
=" yyy",而不是"世界"。
public class Bar
{
public string OneString { get; set; }
[ReadOnly(true)]
public string TwoString { get; set; }
}
public class Foo
{
public Bar MyBar { get; set; }
public int? MyNumber { get; set; }
[ReadOnly(true)]
public string MyString { get; set; }
public string[] MyStringArray { get; set; }
}
internal class Program
{
private static void Main()
{
Foo model = new Foo
{
MyString = "aaa",
MyNumber = 42,
MyBar = new Bar { OneString = "xxx", TwoString = "yyy" }
};
Foo update = new Foo
{
MyString = "bbb",
MyNumber = 77,
MyBar = new Bar { OneString = "hello", TwoString = "world" }
};
MapperConfiguration config = new MapperConfiguration(cfg =>
{
cfg.AllowNullCollections = true;
cfg.CreateMissingTypeMaps = true;
cfg.CreateMap<Foo, Foo>();
cfg.CreateMap<Foo, Foo>().ForAllMembers(opt =>
opt.Condition((source, destination, sourceMember, destMember) =>
(sourceMember != null)));
cfg.ForAllPropertyMaps(map =>
map.SourceMember.GetCustomAttribute<ReadOnlyAttribute>()?.IsReadOnly == true,
(map, configuration) =>
{
configuration.Ignore();
});
});
var mapper = config.CreateMapper();
Foo result = mapper.Map(update, model);
}
}