gpt4 book ai didi

c# - 如何在 AutoMapper 中全局使用忽略?

转载 作者:行者123 更新时间:2023-11-30 21:10:06 25 4
gpt4 key购买 nike

这是现在的样子。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com