system.invalidoperationexception

时间:2013-03-23 11:59:44

标签: c# transactions invalidoperationexception sqlcedatareader

我正在尝试运行此代码

public Exception SetData(string Data , long NoOfColumnsAllowed)
    {
        try
        {
            con = new SqlCeConnection(conectionstring);
            con.Open();
            transaction = con.BeginTransaction();
            com = new SqlCeCommand();
            com.Transaction = transaction;
            com.CommandText = "Select  count(*) from [Copy]";
            com.Connection = con;
            sdr = com.ExecuteReader();
            while (sdr.Read())
            {
                noOfColumns = sdr.GetInt32(0);
            }


            if (noOfColumns > NoOfColumnsAllowed)
            {
                long NoOfColumsToBeDeleted = noOfColumns - NoOfColumnsAllowed;
                com.CommandText = "delete from [Copy] where Sno<=@sno";
                com.Parameters.AddWithValue("@sno", NoOfColumsToBeDeleted);
                com.ExecuteNonQuery();
            }

            com.CommandText = "Insert into [Copy] (Data) values (@data)";
            com.Parameters.AddWithValue("@data", Data);
            com.ExecuteNonQuery();
            transaction.Commit();
            con.Close();

            return null;
        }
        catch (Exception ex)
        {
            try
            {
                transaction.Rollback();
            }
            catch (Exception)
            {

            }
            con.Close();
            return ex;
        }


    }

发生异常 -

  

system.invalidoperationexception:事务不能   如果在此范围内有任何打开的游标,则提交   交易。确保所有数据读取器/结果集都是   在提交更改之前明确关闭。

我是新事务,无法找到有关打开游标的任何有价值的解决方案。代码是否有问题,或者我必须明确关闭数据阅读器,如果是,请告诉我如何?

1 个答案:

答案 0 :(得分:2)

只需调用sdr.Close();在while循环之后,因为这是抱怨的错误。