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

更新Dapper后出现Possible Null Reference Return错误,如何解决?

Dapper更新后的空引用返回问题解析及解决办法

Dapper的核心变更

在支持C#可空引用类型(NRT)的项目中,Dapper更新后调整了QuerySingleOrDefaultAsync<T>的返回类型:从原来的Task<T>改为Task<T?>。这是因为QuerySingleOrDefault的语义本身就是当无匹配记录时返回null,Dapper修正了返回类型的可空性,使其更贴合实际行为,避免调用者忽略空值风险。

你的代码中,方法声明返回Task<T>,但实际调用的Dapper方法返回的是可空的Task<T?>,类型不匹配,因此触发“Possible Null Reference Return”错误。

解决方法

1. 修正方法返回类型(推荐)

直接将方法返回类型改为Task<T?>,明确告知调用者该方法可能返回null,符合代码语义:

public async Task<T?> QuerySingleOrDefault<T>(string sqlStatment, object parameters, CommandType commandType = CommandType.StoredProcedure, int timeout = 90, EnumConnStrings ConnString )
{
    using SqlConnection connection = new SqlConnection(_appSettings.DataSource.GetConnectionById(ConnString));
    return await connection.QuerySingleOrDefaultAsync<T>(sqlStatment, parameters, commandType: commandType, commandTimeout: timeout);
}

2. 强制抑制空引用警告

如果你能通过业务逻辑确保查询必然返回记录,可以使用!空抑制运算符,告诉编译器忽略空值检查:

public async Task<T> QuerySingleOrDefault<T>(string sqlStatment, object parameters, CommandType commandType = CommandType.StoredProcedure, int timeout = 90, EnumConnStrings ConnString )
{
    using SqlConnection connection = new SqlConnection(_appSettings.DataSource.GetConnectionById(ConnString));
    return await connection.QuerySingleOrDefaultAsync<T>(sqlStatment, parameters, commandType: commandType, commandTimeout: timeout)!;
}

3. 主动处理空值场景

如果不允许返回null,可在返回前判断结果,要么返回默认值,要么抛出异常:

public async Task<T> QuerySingleOrDefault<T>(string sqlStatment, object parameters, CommandType commandType = CommandType.StoredProcedure, int timeout = 90, EnumConnStrings ConnString )
{
    using SqlConnection connection = new SqlConnection(_appSettings.DataSource.GetConnectionById(ConnString));
    var result = await connection.QuerySingleOrDefaultAsync<T>(sqlStatment, parameters, commandType: commandType, commandTimeout: timeout);
    return result ?? throw new InvalidOperationException("未找到匹配的记录");
}

4. 临时禁用特定警告

使用#pragma指令仅在当前代码段禁用空引用返回警告:

public async Task<T> QuerySingleOrDefault<T>(string sqlStatment, object parameters, CommandType commandType = CommandType.StoredProcedure, int timeout = 90, EnumConnStrings ConnString )
{
    using SqlConnection connection = new SqlConnection(_appSettings.DataSource.GetConnectionById(ConnString));
#pragma warning disable CS8603 // 可能返回 null 引用。
    return await connection.QuerySingleOrDefaultAsync<T>(sqlStatment, parameters, commandType: commandType, commandTimeout: timeout);
#pragma warning restore CS8603 // 可能返回 null 引用。
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:40:17