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

如何指定Riok.Mapperly为特定属性使用自定义映射方法?

使用Riok.Mapperly为特定属性指定自定义映射方法

针对你遇到的问题,有两种可靠的方式让Mapperly为不同属性调用对应的自定义转换方法:

方法一:通过[MapProperty]特性指定转换方法

使用[MapProperty]特性明确绑定源属性、目标属性,并指定对应的转换方法,让Mapperly精准匹配:

[Mapper]
public static partial class CountryMapper
{
    [MapProperty(nameof(EF.Country.UnderscoreNumbersStr), nameof(M.Country.UnderscoreNumbers), 
        ConversionMethod = nameof(SplitUnderscore))]
    [MapProperty(nameof(EF.Country.PipeNumbersStr), nameof(M.Country.PipeNumbers), 
        ConversionMethod = nameof(SplitPipe))]
    public static partial M.Country ToBoCountry(this EF.Country country);

    private static List<int> SplitUnderscore(string? str)
    {
        return str is null ? [] : [.. str.Split('_').Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse)];
    }

    private static List<int> SplitPipe(string? str)
    {
        return str is null ? [] : [.. str.Split('|').Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse)];
    }
}

通过ConversionMethod参数,为每一对属性映射指定专属的转换方法,避免Mapperly自动匹配时的冲突。

方法二:手动处理特定属性的映射

利用Mapperly的部分方法特性,手动实现需要特殊转换的属性赋值,其余属性由Mapperly自动生成映射逻辑:

[Mapper]
public static partial class CountryMapper
{
    public static partial M.Country ToBoCountry(this EF.Country country);

    // 手动处理特殊属性的映射,Mapperly会自动处理其他属性
    static partial void ToBoCountry(EF.Country source, M.Country destination)
    {
        destination.UnderscoreNumbers = SplitUnderscore(source.UnderscoreNumbersStr);
        destination.PipeNumbers = SplitPipe(source.PipeNumbersStr);
    }

    private static List<int> SplitUnderscore(string? str)
    {
        return str is null ? [] : [.. str.Split('_').Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse)];
    }

    private static List<int> SplitPipe(string? str)
    {
        return str is null ? [] : [.. str.Split('|').Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse)];
    }
}

这种方式更灵活,适合需要额外逻辑处理的场景,Mapperly会在生成的映射代码中自动调用这个手动实现的部分方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:22:11