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)));
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))

        SqlTransaction tx = connection.BeginTransaction(IsolationLevel.ReadCommitted);
            using (SqlCommand cmd = connection.CreateCommand())
                cmd.Transaction = tx;

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!


gvo said...


Torkel Ödegaard said...


Andrew said...

Hey Torkel, I came up on your last post on DotNet Kicks, and I've seen you comment on Alt.Net lately (I think?)

Anyway, just wanted to say this is some nice code and I think it'll be interesting for us to use in the future, so thanks!

It's impressive your blog is brand new and great quality of posting so far!

Definitely subbed :)

Torkel Ödegaard said...

Thanks! That was great to hear :)

Anonymous said...

Hi Torkel,

Could you please show what your SqlCommandHandler looks like?

How's that defined?

Torkel Ödegaard said...

It is a delegate, defined like this:

public delegate void SqlCommandHandler(SqlCommand command);