Skip to content

Unit Of Work

Max Stepanskiy edited this page Feb 6, 2018 · 10 revisions

Unit of work pattern is implemented using ObjectScope class. It provides an ability to Commit/Rollback changes made to a specific object instance. It also starts transaction implicitly when ObjectScope is declared.

using (ObjectScope.New(customer, autoCommit: false))
{
    customer.CompanyName += "Test";
    customer.Orders[0].ShipPostalCode = "11111";
    customer.Orders.RemoveAt(1);

    var o = new Order();
    o.CustomerId = customer.Id;
    o.ShipPostalCode = "19115";
    o.GenerateKey();
    customer.Orders.Add(o);

    // A developer may access original instance to compare property values
    // var hasNewOrders = customer.Old().Orders.Count == customer.Orders.Count;

    // A developer may choose to rollback at any point thus wiping all the changes
    // and resetting the object state
    //customer.Rollback();

    // Since autoCommit option is set to false, a developer must call Commit method
    // in order to preserve object changes; transaction will also be completed at this point
    customer.Commit();
}

Note: ObjectScope implementation uses DialectProvider when generating merge script. Thus unit of work pattern is supported only for databases with DialectProvider implementations. As of now DialectProvider implementations distributed with Nemo are SQL Server (both pre and post SQL Server 2005), MySQL, SQLite, Oracle and PostgreSQL.

Clone this wiki locally