Views: 4.8K
Replies: 1
Archived
|
Getting Unit of Work to work using the Spark reference applicationI am testing out the Unit of Work pattern include in the Spark app. I would expect the unit of work to fail when it hits the exception, except the dispose() method is still called and the transaction completes and adds the cart, but doesn't add the cart item. Am I missing something, or will the transcation only fail if a SQL exception is thrown when inserting the record?
using (var uow = new ArtUnitOfWork()) { var cart = new Cart(true) { Cookie = cookie.Value }; uow.Insert(cart); throw new Exception(); var item = new CartItem(true) { CartId = cart.Id, Quantity = count, ProductId = id, Price = product.Price }; uow.Insert(item); } Mark Erasmus, Oct 10, 2015
|
|
Reply 1Hello Mark:
Indeed, SPARK was not handling the rollbacks properly. The changes below will make it work:(the same changes will be available in the next release of SPARK). In the code-generated Core.cs file insert the following method below the EndTransaction method. public void RollbackTransaction() { if (_transaction != null) { _transaction.Rollback(); _transaction.Dispose(); _transaction = null; if (_connection != null) { _connection.Close(); _connection.Dispose(); _connection = null; } } } Then in the same file you will find a UnitOfWork class. Remove the public virtual void Dispose method and replace it with the following methods: public void Complete() { db.EndTransaction(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { db.RollbackTransaction(); } } Finally, in your own code add the following line just before the closing curly brace: uow.Complete(); This will explicitly commit the transaction. If the Complete method is not called, either by not including it or because of an exception, then the transaction will roll back. Again, the next release of SPARK will include the same corrections. Hope this helps. Jack Jack Poorte, Oct 12, 2015
|