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

HotChocolate GraphQL可空字符串字段contains查询引发空引用异常

解决HotChocolate自定义Contains处理器兼容NULL字段的问题

问题根源是当数据库字段为NULL时,直接调用string.IndexOf方法会触发空引用异常。我们需要在表达式中先添加字段的非空判断,避免对NULL值执行字符串操作。

修改QueryableStringInvariantContainsHandler的HandleOperation方法,增加空值检查逻辑:

public override Expression HandleOperation(
    QueryableFilterContext context,
    IFilterOperationField field,
    IValueNode value,
    object parsedValue)
{
    Expression property = context.GetInstance();
    if (parsedValue is not string str)
        throw new InvalidOperationException();

    // 先判断字段是否为NULL,NULL直接返回false(不匹配)
    var nullCheck = Expression.NotEqual(property, Expression.Constant(null, typeof(string)));
    
    // 原有的不区分大小写包含逻辑
    var containsExpression = Expression.NotEqual(
        Expression.Call(
            property,
            typeof(string).GetMethod("IndexOf", new[] { typeof(string), typeof(StringComparison) }),
            Expression.Constant(str),
            Expression.Constant(StringComparison.OrdinalIgnoreCase)
        ),
        Expression.Constant(-1)
    );
    
    // 组合逻辑:字段非空 且 包含目标字符串
    return Expression.AndAlso(nullCheck, containsExpression);
}

逻辑说明

  1. 空值判断:通过Expression.NotEqual(property, Expression.Constant(null, typeof(string)))检查字段是否不为NULL,若字段是NULL,这部分表达式结果为false。
  2. 组合条件:用Expression.AndAlso将空值判断和包含逻辑组合,只有当字段非空且满足包含条件时,整体结果才为true。既避免了空引用异常,也符合业务逻辑(NULL字段不会匹配任何contains查询)。

修改后的表达式可被Entity Framework Core正确翻译为SQL,在数据库层面完成空值过滤和匹配判断,不会在内存中触发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:04:56