这是现在的样子。 DestinationA 和 DestinationB 派生自某个 DestinationBase 类。我需要忽略所有这些派生类的一些共同属性。是否可以全局应用这些忽略选项而不必对所有派生目标类重复?
Mapper.CreateMap<SourceA, DestinationA>()
.ForMember(d => d.PropA, opt => opt.Ignore())
.ForMember(d => d.PropB, opt => opt.Ignore())
.ForMember(d => d.PropC, opt => opt.Ignore());
Mapper.CreateMap<SourceB, DestinationB>()
.ForMember(d => d.PropA, opt => opt.Ignore())
.ForMember(d => d.PropB, opt => opt.Ignore())
.ForMember(d => d.PropC, opt => opt.Ignore());
我期待这样的事情:
Mapper.CreateMap<DestinationBase>().ForAllSource()
.ForMember(d => d.PropA, opt => opt.Ignore())
.ForMember(d => d.PropB, opt => opt.Ignore())
.ForMember(d => d.PropC, opt => opt.Ignore());
最佳答案
您可以全局忽略所有未映射的属性。 虽然这与 automapper 的主要优点相矛盾,但只允许进行显式映射: 这是用于 Automapper 6 的:
var mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new MyProfile());
// ignore all unmapped properties globally
cfg.ForAllMaps((map, exp) => exp.ForAllOtherMembers(opt => opt.Ignore()));
});
关于c# - 如何在 AutoMapper 中全局使用忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8663771/