在数据访问层中共享连接和事务
我正在为我的 asp.net 应用程序构建数据访问层。 我希望能够在不同类之间共享连接以管理事务,但我不知道该怎么做。
示例:
我有 2 个类,Order 和 OrderDetail。
我将调用我的 DAL Order 类来执行新订单的 SQL 插入。
在 Insert 方法中,我想调用 OrderDetail 类来插入订单的详细信息,并且我将使用相同的连接和事务来执行此操作。
有人可以建议我一些架构设计来做到这一点吗? 或者也许有人可以在互联网上提供一些资源?
我希望这个例子很清楚,我的英语很糟糕!
谢谢。
I'm building a Data Access Layer for my asp.net application.
I would like to be able to share connection between different classes in order to manage transaction, but I don't know how to do that.
Example:
I have 2 classes, Order and OrderDetail.
I will call my DAL Order class for a SQL insert of a new order.
Inside the Insert method, I want to call my OrderDetail class to insert my order's details, and I would do that with same connection and transaction.
Could someone suggest me some architecture design to do that?
Or maybe someone could provide some resource in internet?
I hope the example is clear, my english sucks!
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您专注于共享交易并保留您现在拥有的连接代码。连接是池化的,因此打开连接对性能的影响应该最小。但是,您必须使用相同的事务,否则您插入的订单和订单详细信息就不是原子操作(如果您的代码中途失败,您最终会在数据库中得到不完整的订单)。
“共享”交易的最佳方式是使用 <代码>TransactionScope 类。它创建一个所谓的环境事务。您在环境事务范围内打开的每个
SqlConnection
都会自动成为该事务的一部分。您不再需要使用(或应该使用)
SqlConnection.BeginTransaction
如果您使用环境事务。I suggest you focus on sharing the transaction and leave the connection code as you have it now. Connections are pooled so opening connections should have minimal performance impact. You must use the same transaction however, otherwise your insert of orders and order details isn't an atomic operation (if your code fails halfway, you end up with an incomplete order in your database).
The best way to 'share' your transaction is by using the
TransactionScope
class. It creates a so-called ambient transaction. EverySqlConnection
you open inside the scope of an ambient transaction automatically becomes part of this transaction.You no longer have to use (or should use)
SqlConnection.BeginTransaction
if you use ambient transactions.