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.
The unit of work class serves one purpose: to make sure that when you use multiple repositories, they share a single database context. That way, when a unit of work is complete you can call the SaveChanges method on that instance of the context and be assured that all related changes will be coordinated.
Unit of Work is the concept related to the effective implementation of the repository pattern. non-generic repository pattern, generic repository pattern. Unit of Work is referred to as a single transaction that involves multiple operations of insert/update/delete and so on.
Create the Asp.Net MVC Project with the name of (Repository Design Pattern) screenshots are below. Create an Entity Framework to give the model name DataContext. Select Entity framework designer from the database. Create a Folder in the model folder with the name (DAL) where we will implement our repository.
The Unit of Work is a type of business transaction, and it will aggregate all Repository transactions (CRUD) into a single transaction. Only one commit will be made for all modifications. If any transaction fails to assure data integrity, it will be rolled back.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With