我今天要面对这个问题。我用.NET核心创建了一个API,并创建了一个函数将记录插入到Server数据库中。
SqlCommand.ExecuteNonQuery
返回1,但是当我直接从生成一个SELECT
时,返回0行。准确地说,SELECT
只返回使用手动插入的行。
如果我尝试从插入另一行,我可以看到,即使我没有该行,主键(ID
自动增量)也在增加。
我的代码:
public async Task<bool> InsertAuditTrail(AuditTrailModel auditTrail)
{
bool result = false;
string commandText = String.Concat(@"INSERT INTO [dbo].[AuditTrail] ",
"([NomeApplicazione],[N_Applicazione],[N_Record],[NomeTabella],[NomeCampo],[Utente],[Data],[Insert],[Delete],[Update],[DatoPrecedente],[DatoAggiornato]) ",
"VALUES (@NomeApplicazione, @N_Applicazione, @N_Record, @NomeTabella, @NomeCampo, @Utente, @Data, @Insert, @Delete, @Update, @DatoPrecedente, @DatoAggiornato)");
using (var connection = new SqlConnection(connStr))
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction())
{
using (var command = new SqlCommand(commandText, connection, transaction))
{
try
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@NomeApplicazione", auditTrail.NomeApplicazione);
command.Parameters.AddWithValue("@N_Applicazione", auditTrail.N_Applicazione);
command.Parameters.AddWithValue("@N_Record", auditTrail.N_Record);
command.Parameters.AddWithValue("@NomeTabella", auditTrail.NomeTabella);
command.Parameters.AddWithValue("@NomeCampo", auditTrail.NomeCampo);
command.Parameters.AddWithValue("@Utente", auditTrail.Utente);
command.Parameters.AddWithValue("@Data", auditTrail.Data);
command.Parameters.AddWithValue("@Insert", auditTrail.Insert);
command.Parameters.AddWithValue("@Delete", auditTrail.Delete);
command.Parameters.AddWithValue("@Update", auditTrail.Update);
command.Parameters.AddWithValue("@DatoPrecedente", auditTrail.DatoPrecedente);
command.Parameters.AddWithValue("@DatoAggiornato", auditTrail.DatoAggiornato);
result = command.ExecuteNonQuery() > 0 ? true : false;
}
catch (Exception Ex)
{
await connection.CloseAsync();
errorMsg = Ex.Message.ToString();
}
}
}
}
return result;
}
发布于 2022-11-14 14:26:12
@Selvin在comment中指出了问题:事务需要提交。即使该命令成功执行,在事务提交之前也不会正确插入该行。保留the ()语句也不会提交它。
https://stackoverflow.com/questions/63844633
复制