I don't use NHibernate for everything, so when I do use the ADO.NET API directly I like to use a small static utility class that lets me do this:
Db.Transaction(delegate(SqlCommand cmd) { cmd.CommandText = "DELETE FROM LogEntries WHERE DateCreated < @DateCreated"; cmd.Parameters.AddWithValue("@DateCreated", DateTime.Now.Subtract(TimeSpan.FromDays(30))); cmd.ExecuteNonQuery(); });This simple static method takes care of so much of the repetative code that you never want to write twice, like setting up the connection, registering the transaction, handling the try catch and commit/rollback. Here is the code for the Transaction method:
public static void Transaction(SqlCommandHandler handler) { using (SqlConnection connection = new SqlConnection(Settings.CommonDb)) { connection.Open(); SqlTransaction tx = connection.BeginTransaction(IsolationLevel.ReadCommitted); try { using (SqlCommand cmd = connection.CreateCommand()) { cmd.Transaction = tx; handler(cmd); } tx.Commit(); } catch { tx.Rollback(); throw; } } }
The C# language became a lot more power in the 2.0 update when anonymous methods (i.e. closures) were introduced, and the 3.0 update that introduced the lambda syntax made it even better. If it weren't for these new features of C# I would probably be compelled to move to ruby!