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

.NET POST请求中ExpedienteId莫名变为0的问题求助

问题根源分析

你的核心问题在于错误使用ExecuteScalarAsync<int>执行INSERT语句:

  • 普通INSERT语句默认不会返回任何值,ExecuteScalarAsync<int>会返回int类型的默认值0,执行后这个值直接覆盖了原本正确的expediente.ExpedienteId(26),导致最终ID变为0。
  • 由于ExpedienteId是用户自定义的非自增字段,你完全不需要从数据库获取这个ID,根本不该用ExecuteScalarAsync来执行插入操作。
解决方案

修改代码,用Dapper的ExecuteAsync替代ExecuteScalarAsync<int>,并且不需要对expediente.ExpedienteId进行赋值:

public async Task<Expedientes> AgregarPrimerMovimiento(Expedientes expediente)
{
    using (var conexion = _baseProduccion.Conexion)
    {
        var sql = 
              $"INSERT INTO Movimiento (ExpedienteId,FechaIngreso,SectorOrigen,SectorDestino,FechaEnvio) SELECT @ExpedienteId,@FechaCreacion,@TipoDocumentoId,@UltimoSector,@FechaModificacion";
           
        var parametrosExpediente = new
        {
            @ExpedienteId = expediente.ExpedienteId,
            @TipoDocumentoId = expediente.TipoDocumentoId.Value,
            @Descripcion = expediente.Descripcion,
            @FechaCreacion = expediente.FechaCreacion,
            @FechaModificacion = expediente.FechaModificacion,
            @UltimoSector = expediente.UltimoSector.Value,
            @Estado = expediente.Estado,
        };

        // 用ExecuteAsync执行插入,无需返回值
        await conexion.ExecuteAsync(sql, parametrosExpediente);
        return expediente;
    }
}
补充说明
  1. 关于ExecuteNonQueryAsync:IDbConnection本身没有这个方法,但Dapper提供了ExecuteAsync扩展方法,只要代码中引用了using Dapper;命名空间,即可正常使用。
  2. 直接执行SQL测试正常的原因:直接运行INSERT语句时,数据库不会返回值,也就不存在覆盖原有ID的问题,代码中错误用ExecuteScalarAsync接收返回值才导致了异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:15:59