Reputation: 10291
I'm not 100% sure that I've implemented my Repository and UnitOfWork patterns correctly, but then I can't see how else this will work.
For example, I have two objects, Apple and Orange.
Apple is joined to Orange via an OrangeID like so:
public class Apple
{
public int OrangeID { get; set; }
}
I want to create a new Apple and a new Orange, and I want to set the ID link up appropriately. But I have a problem. I won't know the OrangeID until I have saved the Orange to the database.
So this means I will have the following:
var unitOfWork = new UnitOfWork();
Orange newOrange = new Orange();
OrangeRepository.Insert(newOrange);
unitOfWork.Commit();
//newOrange will have been updated with the actual ID
Apple newApple = new Apple(newOrange.ID);
etc...
This is not an atomic operation, unless I have a transaction that sits outside the above. But I thought that was what UnitOfWork was supposed to handle? Or should my UnitOfWork.Commit() assign the appropriate values when it's writing to the database?
Any help/tips would be appreciated, thanks Duncan
Upvotes: 1
Views: 932
Reputation: 2187
First, I can't see this as a relation between an Apple and Orange entities. It's just an Apple has a numeric attribute called OrangeID. Your code should be like:
Apple apple = new Apple(newOrange);
AppleRepository.Insert(apple);
unitOfWork.Commit();
Then, you may check If db relation has been established correctly. So now there is no proof If your unit-of-work implementation works or not.
Moreover, There are many available implementations, If you want to save some of your time.
Although, I already re-invented the wheel and I use an implementation of mine :)
If you'd like to have a peek It's hosted on google code: ws-helpers project. I need time to make this as a stand-alone project because It was actually part of a previous project.
Sure, the most famous implementation is Rhino-Tools/UnitOfWork. But, I prefer mine because I can create as many units as I need, each with a separate transaction, while in Rhino-Tools there is always only one current unit. But I'm not yet sure about the thread-safety of current implementation.
Upvotes: 1