// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Data.SqlClient; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Data.Linq.SqlClient; namespace E { [Table(Name="dummy")] public class Dummy { [Column(Name="id",IsPrimaryKey=true)] public int Id; [Column(Name="txt")] public string Txt; } public class CommitOrRollback { private SqlConnection con; DataContext db; public void Setup() { con = new SqlConnection(@"Server=ARNEPC3\SQLEXPRESS;Integrated Security=SSPI;Database=Test"); con.Open(); SqlCommand cre = new SqlCommand("CREATE TABLE dummy(id INTEGER, txt VARCHAR(50), PRIMARY KEY(id))", con); cre.ExecuteNonQuery(); db = new DataContext(con); } public void Check() { Console.WriteLine("Data:"); Table dummies = db.GetTable(); foreach(Dummy d in dummies) { Console.WriteLine(" " + d.Id + " " + d.Txt); } } private int n = 0; public void Test(bool commit) { SqlTransaction tx = con.BeginTransaction(); db.Transaction = tx; Dummy d1 = new Dummy(); n++; d1.Id = n; d1.Txt = "This is test #" + n; db.GetTable().InsertOnSubmit(d1); db.SubmitChanges(); Console.WriteLine("INSERT of " + d1.Id); Dummy d2 = new Dummy(); n++; d2.Id = n; d2.Txt = "This is test #" + n; db.GetTable().InsertOnSubmit(d2); db.SubmitChanges(); Console.WriteLine("INSERT of " + d2.Id); if(commit) { tx.Commit(); Console.WriteLine("COMMIT"); } else { tx.Rollback(); Console.WriteLine("ROLLBACK"); } } public void TearDown() { SqlCommand drp = new SqlCommand("DROP TABLE dummy", con); drp.ExecuteNonQuery(); con.Close(); } public static void Main(string[] args) { CommitOrRollback o = new CommitOrRollback(); o.Setup(); o.Check(); o.Test(true); o.Check(); o.Test(false); o.Check(); o.TearDown(); } } }