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

C#实现检查数据库记录是否存在的API端点返回布尔值异常问题

问题解决思路

错误原因

你调用的_offerRepository中的方法是无返回值(void)类型,所以无法将它的执行结果赋值给变量result——这就是报错cannot assign void to an implicitly-typed local variable的直接原因。

解决步骤

  1. 修正仓储层方法的返回类型
    你需要让仓储方法返回能判断记录存在性的结果,比如Task<bool>或Task<int>(存储过程返回1表示存在、0表示不存在)。示例:

    // 仓储层示例方法
    public async Task<bool> CheckOfferExistsAsync(int offerId)
    {
        // 执行存储过程并获取返回值
        var returnValue = new SqlParameter("@ReturnValue", SqlDbType.Int) { Direction = ParameterDirection.ReturnValue };
        await _dbContext.Database.ExecuteSqlRawAsync(
            "EXEC @ReturnValue = CheckOfferExists @OfferId",
            returnValue,
            new SqlParameter("@OfferId", offerId)
        );
        // 根据存储过程返回值判断存在性
        return (int)returnValue.Value == 1;
    }
    
  2. 调整API端点逻辑
    调用修改后的仓储方法,直接返回判断结果即可:

    [HttpGet("exists/{offerId}")]
    public async Task<IActionResult> CheckOfferExists(int offerId)
    {
        var exists = await _offerRepository.CheckOfferExistsAsync(offerId);
        return Ok(exists);
    }
    
  3. 排查“始终返回True”的问题
    之前的逻辑因为没有正确获取存储过程的执行结果,直接返回true,所以不管数据库中是否存在记录都会返回True。通过上述方式获取存储过程的返回值并判断,就能解决这个问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:50:24