共享连接和事务在一个数据访问层 [英] Sharing connection and transaction in a Data Access Layer

查看:205
本文介绍了共享连接和事务在一个数据访问层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个数据访问层为我的asp.net应用程序。 我希望能够分享,以管理交易不同阶层之间的连接,但我不知道该怎么做。

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.

例如:

我有2个班,秩序和的OrderDetail。

I have 2 classes, Order and OrderDetail.

我会打电话给我的DAL Order类的一个新秩序的SQL插入。

I will call my DAL Order class for a SQL insert of a new order.

在插入的方法,我想打电话给我的OrderDetail类插入我的命令的详细信息,我会做到这一点与同样的连接和事务。

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!

感谢。

推荐答案

我建议你专注于分享的交易,并留下了联系code,因为你现在拥有它。连接池,以便打开连接应有性能的影响最小。您必须然而,使用相同的交易,否则您的订单和订单详细信息的插入是不是一个原子操作(如果你的code中途失败,你最终以一个未完成订单在数据库中)

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).

要分享最好的办法您的交易是通过使用的 的TransactionScope 类。它创建了一个所谓的环境事务。每个的SqlConnection 你一个环境事务的范围内打开自动成为交易的一部分。

The best way to 'share' your transaction is by using the TransactionScope class. It creates a so-called ambient transaction. Every SqlConnection you open inside the scope of an ambient transaction automatically becomes part of this transaction.

您不再需要使用(或应该使用)<一href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.begintransaction.aspx"相对=nofollow> SqlConnection.BeginTransaction 如果你使用的环境事务。

You no longer have to use (or should use) SqlConnection.BeginTransaction if you use ambient transactions.

这篇关于共享连接和事务在一个数据访问层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆