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

给Mapster映射添加自定义逻辑:AfterMapping空引用问题与优化需求

Mapster映射中为Entries设置递增ID的问题及优化方案

问题背景

需要将Input类型映射到Output类型,同时为Output.Entries集合中的每个元素设置递增的Id值(即Entries[0].Id = 1,Entries[1].Id = 2,以此类推)。最初尝试通过AfterMapping实现该逻辑:

[Mapper]
public interface IMyMapper {
    Output Map(Input userTableTemplate);
}

public class RegisterMyMapper : IRegister {
    public void Register(TypeAdapterConfig config) {
        config.NewConfig<Input, Output>()
            .Map(output => output.OutputName, input => input.Name)
            .AfterMapping(output => {
                foreach (var pair in output.Entries.Select((value, index) => new {value = value, index = index})) {
                    pair.value.Id = pair.index + 1;
                }
            });
    }
}

public class Output {
    public string OutputName { get; set; }
    public IEnumerable<Entry> Entries { get; set; }
}

public class Entry { public int Id { get; set; } }

public class Input { public string Name { get; set; } }

但执行_myMapper.Map(myInput)时触发空引用异常,原因是Mapster生成的映射类中,私有委托成员Action1未被初始化,直接调用Action1.Invoke(result)导致异常:

public partial class MyMapper : IMyMapper
{
    private Action<Output> Action1;
    
    public Output Map(Input p1)
    {
        if (p1 == null)
        {
            return null;
        }
        Output result = new Output();
        
        result.OutputName = p1.Name;
        Action1.Invoke(result);
        return result;
    }
}

当前解决方案

将AfterMapping替换为AfterMappingInline,并编写扩展方法封装ID赋值逻辑:

config.NewConfig<Input, Output>()
    .Map(output => output.OutputName, input => input.Name)
    .AfterMappingInline(output => output.Entries.SetIdValues())

扩展方法实现:

public static class MethodExtensions {
    public static void SetIdValues(this IEnumerable<Entry> entries) {
        foreach (var pair in entries.Select((value, index) => new {value = value, index = index}))
            pair.value.Id = pair.index + 1;
    }
}

更优雅的解决方案

无需额外编写扩展方法,直接在AfterMappingInline中内联处理逻辑,利用C#元组语法简化循环,同时增加空值检查避免潜在异常:

config.NewConfig<Input, Output>()
    .Map(output => output.OutputName, input => input.Name)
    .AfterMappingInline(output => 
    {
        if (output.Entries is not null)
        {
            foreach (var (entry, index) in output.Entries.Select((e, i) => (e, i)))
            {
                entry.Id = index + 1;
            }
        }
    });

这种方式既保持了代码的紧凑性,又避免了额外的扩展方法依赖,同时通过空值检查提升了代码的健壮性。

内容的提问来源于stack exchange,提问作者Tar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:15:35