13

I'm trying to find an example implementation of the Unit Of Work pattern in Simple.Data. Does anybody have one? I'm currently using non generic repositories and have been told that implementing UoW is something to do.

casperOne
  • 73,706
  • 19
  • 184
  • 253
Phil
  • 4,012
  • 5
  • 39
  • 57

1 Answers1

15

If what you want from the Unit of Work is a set of insert/update/delete operations covered by a transaction, then that is supported:

var db = Database.Open();
var tx = db.BeginTransaction(); // Internal IDbConnection opened by this call
try
{
    order = tx.Orders.Insert(order); // Returned record will have new IDENTITY value
    foreach (var item in items)
    {
        item.OrderId = order.Id;
        tx.Items.Insert(item);
    }
    tx.Commit(); // Internal IDbConnection closed by this call...
}
catch
{
    tx.Rollback(); // ...or this call :)
}

(Note: this code assumes you're using the Ado adapter, and IDENTITY refers to SQL Server, but the code will work on any of the Ado providers and on any adapter which supports transactions.)

If you want to be able to create a batch of operations and run them all in one go, then that's not directly supported at the moment, but I'm open to feature requests or patches.

If you're after change tracking on objects, one thing that might help to know is that as of Simple.Data 0.9, SimpleRecord implements ICloneable, so you can take a copy of a record just after selecting it and use it for comparison when saving back. I'm going to push a release soon with support for an Update(current, original) method which will do optimistic-concurrency updates.

Mark Rendle
  • 9,274
  • 1
  • 32
  • 58
  • 1
    Incidentally, it blows my mind that Simple.Data has its own tag on StackOverflow! – Mark Rendle Aug 12 '11 at 00:48
  • Wow, its solves what I wanted (a way to better handle inserting many rows!) – Phil Aug 12 '11 at 14:48
  • 1
    If you're just inserting lots of rows, the Insert method will also take an IEnumerable and run all the inserts with a single connection, regardless of whether you're in a transaction or not. It also returns an IEnumerable with the newly inserted rows. Same with Update. The only thing that's not supported is running multiple heterogeneous operations in a batch. – Mark Rendle Aug 13 '11 at 09:48
  • That new overload to do Update(current, original) is in 0.9.1, which just landed on NuGet. – Mark Rendle Aug 18 '11 at 18:27