You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Condition method checks if the source Dto's Id equals 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's IsActive to true (as per your rule).
  • Ignoring when Id !=0: When the condition fails (Id is not 0), AutoMapper skips mapping the IsActive field entirely. This means the existing value of Entity.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:05:23