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

如何在TinyMapper的Bind绑定表达式中添加嵌套属性空值检查

解决方案

你可以通过以下3种常用方式实现空值检查,避免空引用异常:

1. 直接在绑定逻辑中加非空判断(适合单独映射内层字段的场景)

在取值委托中加三元运算符做非空校验,源属性为空时直接返回对应类型的默认值即可:

TinyMapper.Bind<SourceClass, DestinationClass>(config => {
    config.Bind(
        source => source.CommonSource != null ? source.CommonSource.Id : default(int),
        target => target.CommonDestination.Id
    );
});

2. 绑定整个导航属性(优先推荐,代码最简洁)

提前注册两个公共类的映射关系,直接绑定外层的CommonSource和CommonDestination属性,TinyMapper原生会自动处理源属性为空的场景,不会抛出空引用异常:

// 先注册公共类的映射
TinyMapper.Bind<CommonClassSource, CommonClassDestination>();

TinyMapper.Bind<SourceClass, DestinationClass>(config => {
    config.Bind(
        source => source.CommonSource,
        target => target.CommonDestination
    );
});

3. 配合AfterBind回调实现复杂空值逻辑

如果源属性为空时,你需要给目标属性初始化默认实例而非留空,可以加AfterBind回调处理:

TinyMapper.Bind<SourceClass, DestinationClass>(config => {
    config.Bind(
        source => source.CommonSource != null ? source.CommonSource.Id : default(int),
        target => target.CommonDestination.Id
    );
    config.AfterBind((source, target) => {
        // 目标属性为空时初始化默认实例
        target.CommonDestination ??= new CommonClassDestination();
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:45:03