我有以下代码,但不知道为什么会出现以下错误:"ExecuteNonQuery需要在命令所分配的连接处于等待本地事务状态时具有事务。 命令的Transaction属性尚未初始化"。我正在使用SQL事务。请问有人能帮助我吗?
protected void RunLeave(int posID, int tot, int rowid)
{
using (SqlConnection con = new SqlConnection(Modfunctions.configstring))
{
con.Open();
SqlDataReader dr = default(SqlDataReader);
int i = 0;
try
{
SqlCommand cmd = new SqlCommand("Select ID from Employee WITH(Nolock) WHERE PositionID=@a", con);
cmd.Parameters.Add("@a", SqlDbType.Int).Value = posID;
//cmd.Transaction = transaction;
dr = cmd.ExecuteReader();
if (dr.HasRows)
using (SqlConnection cons = new SqlConnection(Modfunctions.configstring))
{
cons.Open();
SqlTransaction transaction = cons.BeginTransaction(DateTime.Now.ToLongTimeString());
SqlCommand cm = new SqlCommand();
cm.Transaction = transaction;
cm.Connection = cons;
while (dr.Read())
{
cm.CommandText="INSERT INTO LeaveAssignmentEntry VALUES('" + rowid + "','" + ddl.SelectedItem.Text + "','" + dr[0].ToString() + "','" + tot + "','" + tot + "','0')";
cm.ExecuteNonQuery();
i++;
}
transaction.Commit();
}
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('" + i + " employee(s) run successfully')", true);
}
catch (Exception ex)
{
try
{
//transaction.Rollback();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('" + ex.Message.Replace("'", "") + "')", true);
}
catch (Exception ex1)
{
}
}
}
}
cm
对象的创建移到了循环外面。为什么?现在你正在尝试重复使用同一个对象,而不是创建新的对象。错误似乎暗示着在事务仍然打开的情况下无法重复使用它。尝试将它移回到之前的位置。 - David