65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 TableAdapter 进行事务处理

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.30/5 (6投票s)

2007年2月18日

CPOL

1分钟阅读

viewsIcon

105828

downloadIcon

1036

使用TableAdapter进行事务处理。

引言

如何在单个事务中更新两个TableAdapter?我真的对这个问题感到惊讶,我原本以为这会是一个基本功能。

我将使用Northwind数据库作为示例。我想向Order和Order Details表添加新的记录。我想使用事务来完成此操作。我不想在没有订单详情的情况下添加订单。并且,我想使用TableAdapter。

问题

问题在于TableAdapter没有公开Connection属性或Transaction属性,那我该如何做?!真不知道!幸运的是,反射、Google和Ryan Whitaker拯救了我(们)。

解决方案

  • 0. 初始化连接,开始事务。
  • 1. 使用反射访问要使用事务的TableAdapter(s)的SqlDataAdapter
  • 2. 将此适配器的Insert/Update/Delete Connection属性设置为创建事务的连接。
  • 3. 将此适配器的Insert/Update/Delete Transaction属性设置为适当的事务。
  • 4. 对需要在事务中更新的每个TableAdapter执行此操作。
  • 5. 提交事务。

换句话说

0.
conn = new SqlConnection(Properties.Settings.Default.NorthwindConnectionString);
conn.Open();
trans = conn.BeginTransaction();
1. 
public SqlDataAdapter GetAdapter(object tableAdapter)
{
    Type tableAdapterType = tableAdapter.GetType();
    SqlDataAdapter adapter = (SqlDataAdapter)tableAdapterType.GetProperty("Adapter", 
           BindingFlags.Instance | BindingFlags.NonPublic).GetValue(tableAdapter, null);
    return adapter;
}
2.
adapter.InsertCommand.Connection = trans.Connection;
adapter.UpdateCommand.Connection = trans.Connection;
adapter.DeleteCommand.Connection = trans.Connection;

3.
adapter.InsertCommand.Transaction = trans;
adapter.UpdateCommand.Transaction = trans;
adapter.DeleteCommand.Transaction = trans;

4. 
-

5. 
trans.commit();

下载附件中的项目以获取一个可用的示例。

请确保将此行代码更改为您的适当数据库连接

Properties.Settings.Default.NorthwindConnectionString = 
   @"Data Source=kenny2;Initial Catalog=Northwind;Integrated Security=True";
© . All rights reserved.