我尝试执行以下代码时收到此错误消息.
ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction
任何人都可以建议问题出在哪里?我想问题的根源是我尝试执行存储过程的部分.
存储过程在执行时创建自己的事务
using (sqlConnection conn = new sqlConnection(connStr)) { conn.open(); sqlCommand command = conn.CreateCommand(); sqlTransaction transaction; // Start a local transaction. transaction = conn.BeginTransaction("createOrder"); // Must assign both transaction object and connection // to Command object for a pending local transaction command.Connection = conn; command.Transaction = transaction; try { command.CommandText = "INSERT INTO rand_resupply_order (study_id,centre_id,date_created,created_by) " + "VALUES (@study_id,@centre_id,@date_created,@created_by) SET @order_id = ScopE_IDENTITY()"; command.Parameters.Add("@study_id",sqlDbType.Int).Value = study_id; command.Parameters.Add("@centre_id",sqlDbType.Int).Value = centre_id; command.Parameters.Add("@date_created",sqlDbType.DateTime).Value = DateTime.Now; command.Parameters.Add("@created_by",sqlDbType.VarChar).Value = username; sqlParameter order_id = new sqlParameter("@order_id",sqlDbType.Int); //study_name.Value = order_id.Direction = ParameterDirection.Output; command.Parameters.Add(order_id); command.ExecuteNonQuery(); command.Parameters.Clear(); //loop resupply list for (int i = 0; i < resupplyList.Count(); i++) { try { sqlCommand cmd = new sqlCommand("CreateOrder",conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@study_id",sqlDbType.Int).Value = study_id; cmd.Parameters.Add("@centre_id",sqlDbType.Int).Value = centre_id; cmd.Parameters.Add("@created_by",sqlDbType.VarChar).Value = username; cmd.Parameters.Add("@quantity",sqlDbType.VarChar).Value = resupplyList[i].Quantity; cmd.Parameters.Add("@centre_id",sqlDbType.Int).Value = centre_id; cmd.Parameters.Add("@depot_id",sqlDbType.VarChar).Value = depot_id; cmd.Parameters.Add("@treatment_code",sqlDbType.Int).Value = centre_id; cmd.Parameters.Add("@order_id",sqlDbType.Int).Value = (int)order_id.Value; cmd.ExecuteNonQuery(); } catch (sqlException ex) { transaction.Rollback(); ExceptionUtility.LogException(ex,"error"); throw ex; } catch (Exception ex) { transaction.Rollback(); ExceptionUtility.LogException(ex,"error"); throw ex; } finally { conn.Close(); conn.dispose(); } } return (int)order_id.Value; } catch (Exception ex) { transaction.Rollback(); ExceptionUtility.LogException(ex,"error"); throw ex; } finally { // Attempt to commit the transaction. transaction.Commit(); conn.Close(); conn.dispose(); command.dispose(); }
解决方法
使用事务时,你应该在任何地方使用它.
cmd.Transaction = transaction;
原文地址:https://www.jb51.cc/csharp/98082.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。