Automapper 9.0双向成员验证遇无Flags属性警告,是否可依赖?
Great question—this is a common point of confusion with AutoMapper's MemberList enum! Let's break this down clearly.
First, let's answer your core concern: your current code using MemberList.Source | MemberList.Destination does work as intended, and it's not just a lucky accident. Even though the MemberList enum doesn't have the [Flags] attribute, AutoMapper's internal logic explicitly handles bitwise combinations of these values to enable bidirectional member validation. The compiler warning you see is just C# flagging the operation as potentially risky when an enum isn't marked with [Flags]—but AutoMapper was designed to support this usage.
That said, there's a cleaner, officially intended way to get the same result without the warning: use MemberList.All. This enum value is purpose-built to validate both source and destination members, which is exactly what you're aiming for with the bitwise OR. Your code can be rewritten like this to be more idiomatic:
CreateMap<IViewCreationData, View>() .ValidateMemberList(MemberList.All) .ForMember(dest => dest.aaa, opt => opt.MapFrom(src => src.a)) .ForMember(dest => dest.bbb, opt => opt.MapFrom(src => src.b)) .ForMember(dest => dest.ccc, opt => opt.Ignore()) .ForMember(dest => dest.ddd, opt => opt.Ignore()) .ForSourceMember(src => src.eee, opt => opt.DoNotValidate());
Is your original approach reliable for future versions?
While AutoMapper has supported the bitwise combination of Source and Destination for years (including 9.0 and all newer releases), using MemberList.All is the more maintainable choice. It aligns with AutoMapper's official design, eliminates compiler warnings, and makes your intent instantly clear to other developers reading the code.
To sum up:
- Your current code works and will likely continue to work in future versions
- But switching to
MemberList.Allis the better practice for this use case
内容的提问来源于stack exchange,提问作者Volker

