Search code examples
c#asp.netsqltransaction

Can any one tell whats' wrong in my transaction


Hi all i have written the following transaction to insert data but when i am getting an exception only the data which got the exception not inserting to db the remaining all are inserting

This is what i wrote

public bool addWhole(SqlTransaction osqlTrans)
{
   m_flag = false;
   osqlTrans = null;

    SqlConnection osqlCon = new SqlConnection(constr);

    if (osqlCon.State != ConnectionState.Open)
    {
        osqlCon.Open();
    }

    osqlTrans = osqlCon.BeginTransaction();

    try
    {
      if (this.addRisk(osqlTrans, osqlCon))
      {
       if (this.addEconomical(osqlTrans, osqlCon))
       {
           osqlTrans.Commit();
       }
      }
     }
    catch (Exception ex)
    {
        osqlTrans.Rollback();
    }
    finally
    {
        osqlCon.Close();
    }
    return m_flag;
}

public bool addRisk(SqlTransaction oRiskTrans, SqlConnection oRiskConn)
{
     con = new SqlConnection(constr);
    if (con.State != ConnectionState.Open)
    {
        con.Open();
    }
    cmd = new SqlCommand("insert into tblEnrollmentData (EID,Eyear,Epercent) values('" + id + "','" + str + "','" + dbPercent + "')", con); //Even i tried adding transaction in command statement
            if (cmd.ExecuteNonQuery() > 0)
            {
                m_flag = true;
            }
   }

public bool addEconomical(SqlTransaction oRiskTrans, SqlConnection oRiskConn)
{
     con = new SqlConnection(constr);
    if (con.State != ConnectionState.Open)
    {
        con.Open();
    }
    cmd = new SqlCommand("insert into tblEnrollmentData (EID,Eyear,Epercent) values('" + id + "','" + str + "','" + dbPercent + "')", con);//Even i tried adding transaction in command statement
            if (cmd.ExecuteNonQuery() > 0)
            {
                m_flag = true;
            }
   }

I tried to rollback the transaction by failing the second condition but my first statement is inserting to DB.. What should i do in order to overcome this


Solution

  • I'm guessing its one of these things

    1) You are not using the same connection object for all the different commands
    2) You are not assigning the transaction to the commands before you execute them
    3) Both perhaps

    Try using the same connection object and assigning the transaction to the command before you execute it for an example see this page on MSDN. http://msdn.microsoft.com/en-us/library/86773566.aspx