工作单元和 L2S DataContext

发布于 2024-07-25 22:18:14 字数 398 浏览 9 评论 0原文

为您的模式专家快速提问。

我想要一个与实际数据访问技术分离的存储库模式,因为我还没有决定这一点,并且我希望它是灵活的。 因此,这可以是 L2S、L2E、NHibernate、Lightspeed 或任何其他形式。

但我对这个 UnitOfWork 的事情感到困惑。

在 L2S 世界中,这似乎就是您的 DataContext。

但是对于非 L2S 世界呢?例如,假设我使用手写 SQL。

我的问题是谁做什么? 在我的 Repo.Save() 方法中,是否应该调用 UnitOfWork.Commit 然后生成所需的 INSERT/UPDATE SQL ?

不期待明确的答案,但进行一些讨论会很好,只是为了确保我走在正确的轨道上!

谢谢

Quick Q for you pattern experts out there.

I want a Repository pattern that is de-coupled from the actual data access tech, as I've not decided on that yet and I want it to be flexible. So, this could be L2S, L2E, NHibernate, Lightspeed or anything.

But I'm getting confused about this UnitOfWork thing.

In the L2S world, this seems to be your DataContext.

But what about a non-L2S world, imagine I was using hand-written SQL for example.

My question is who does what? In my Repo.Save() method, should this call the UnitOfWork.Commit which then generates the required INSERT/UPDATE SQL ?

Not expecting a definite answer, but some discussion would be good, just to make sure I'm on the right track!

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟雨凡馨 2024-08-01 22:18:14

存储库当然可以对工作单元对象调用提交/保存/提交,或者它们可以将其留给消费者。 我更喜欢后一种情况,因为它使消费者能够控制工作单元实例的生命周期,从而允许消费者参与多个存储库:

// 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

Repositories certainly can call commit/save/submit on the unit of work object, or they could leave this up to the consumer. I prefer the latter scenario, because it enables the consumer to control the lifetime of the unit of work instance, which allows the consumer to engage multiple repositories:

// 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文