Click here to Skip to main content
15,906,574 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I use transaction for tow table?
For example we have tow table (main and detail), when I insert one record in main table, may insert SOME record in detail with for loop(MORE THAN ONE RECORD). I need control tow table with transaction on time.
Posted
Comments
Tejas Vaishnav 23-Oct-13 8:35am    
what method you use to insert your records in master and detail.
you use linq to sql or simple ado.net type?

yes you can set transaction for inserting/updating tables more than 1
1. For that you have to add detail objects in list
2. Send parent and details object at a time to BLL
3. In BLL apply transaction
4. This will apply transaction to parent as well as details transacations
 
Share this answer
 
you can do something like this...

1) create connection
2) create transaction
3) insert master record using that transaction (but do not commit it)
4) insert details record(s)
5) if all the thing is going good then commit the transaction or if error occurred rollback transaction.

something like this...


C#
SqlConnection db = new SqlConnection("connstringhere");
      SqlTransaction transaction;

      db.Open();
      transaction = db.BeginTransaction();
      try 
      {
         new SqlCommand("INSERT INTO master " +
            "(Text) VALUES ('Row1');", db, transaction)
            .ExecuteNonQuery();
         for(int i =0; i<10;i++){
         new SqlCommand("INSERT INTO details VALUES " +
            "( " + i + ");", db, transaction)
            .ExecuteNonQuery();
           }
         transaction.Commit();
      } 
      catch (SqlException sqlError) 
      {
         transaction.Rollback();
      }
      db.Close();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900