2009-06-21 25 views
0

爲您提供Quick Q模式專家。工作單位和L2S DataContext

我想要一個與實際數據訪問技術分離的Repository模式,因爲我還沒有確定這個模式,我希望它是靈活的。所以,這可能是L2S,L2E,NHibernate,Lightspeed或其他。

但是我對這個UnitOfWork的事情感到困惑。

在L2S世界裏,這似乎是你的DataContext。

但是非L2S世界呢,想象一下我使用的是手寫SQL。

我的問題是誰在做什麼?在我的Repo.Save()方法中,是否應該調用UnitOfWork.Commit,然後生成所需的INSERT/UPDATE SQL?

不期待一個明確的答案,但一些討論會很好,只是爲了確保我走在正確的軌道上!

感謝

回答

1

庫當然可以調用commit /保存/提交工作對象的單位,或者他們可以離開這個由消費者。我更喜歡後一種情況,因爲它使消費者能夠控制工作單元實例的使用期限,從而允許消費者使用多個存儲庫:

// outside the repository layer 
// int productId defined elsewhere 
// int quantity defined elsewhere 

IUnitOfWork unitOfWork = ... instantiate/get a new instance of your DataContext ... 

ProductRepository productRepository = new ProductRepository(unitOfWork); 
Product product = productRepository.GetById(productId); 

Order order = new Order(); 
order.AddOrderLine(product, quantity); 

OrderRepository orderRepository = new OrderRepository(unitOfWork); 
orderRepository.Add(order); 

unitOfWork.Save(); // This calls SubmitChanges() on the DataContext 
+0

這種方法很少出錯。 1)持久性技術通過使用DataContext(L2S)泄露到域中。 2)DataContext可以在存儲庫上下文之外使用,客戶端可以簡單地使用DataContext生成他們自己的查詢,因此不需要存儲庫。 – 2009-11-07 05:57:49