AutoMapper中依据ID值控制IsActive字段映射规则的实现方法
AutoMapper Conditional Mapping for IsActive Field
First, let's fix a small typo in your code snippet: you're targeting dto.Active in ForMember, but we need to map to the Entity's IsActive property instead. Here's the complete configuration that implements your desired rules:
CreateMap<Dto, Entity>(MemberList.Source) .ForMember(dest => dest.IsActive, opt => { // Only apply this mapping when the source Dto's Id is 0 opt.Condition(src => src.Id == 0); // Set the destination IsActive to true when the condition is met opt.MapFrom(_ => true); });
How this works:
- Condition: The
Conditionmethod checks if the sourceDto'sIdequals 0. This tells AutoMapper to only process this member mapping when the condition is true. - MapFrom: When the condition passes (Id=0), we explicitly set the
Entity'sIsActivetotrue(as per your rule). - Ignoring when Id !=0: When the condition fails (Id is not 0), AutoMapper skips mapping the
IsActivefield entirely. This means the existing value ofEntity.IsActive(if you're updating an existing entity) remains unchanged, which aligns with your "ignore the field" requirement.
Important Note:
Your Dto retains the IsActive field as needed for passing to clients—this configuration only affects the mapping from Dto to Entity, so the Dto's property remains intact for your client-facing logic.
内容的提问来源于stack exchange,提问作者harishr
相关产品推荐
相关产品推荐

