المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Rate this tricky code : Use multiple TableAdapters within a single transaction!



C# Programming
04-29-2009, 12:31 AM
Hi everybody
after a lot of weeks about update related tables in database in a single transaction and configuring TableAdapters with stored procedures for CRUD operations, and having many trouble with TableAdapterManager.UpdateAll method to do this (see this post), i decide write some tricky code to do this myself and i put this code here for discussion :

Note : i have 2 tables, Customers & Orders. The Customers table is a parent of Orders table



TestDataSet ds = new TestDataSet();

private void toolStripButton1_Click(object sender, EventArgs e)
{
if (ds.Customers.GetChanges() != null || ds.Orders.GetChanges() != null)
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TestConnectionString))
{
SqlTransaction tr = null;
try
{
if (con.State != ConnectionState.Open)
con.Open();
tr = con.BeginTransaction();
if (ds.Customers.GetChanges() != null)
{
TestDataSetTableAdapters.CustomersTableAdapter customersAdapter = new TransactionalUpdate.TestDataSetTableAdapters.CustomersTableAdapter();

// Set connection and transaction of TableAdapter to current connection and transaction (con,tr)
customersAdapter.Connection = con;
customersAdapter.Adapter.InsertCommand.Transaction
= customersAdapter.Adapter.UpdateCommand.Transaction
= customersAdapter.Adapter.DeleteCommand.Transaction = tr;
customersAdapter.Update(ds.Customers.GetChanges() as TestDataSet.CustomersDataTable);
}
if (ds.Orders.GetChanges() != null)
{
TestDataSetTableAdapters.OrdersTableAdapter ordersAdapter = new TransactionalUpdate.TestDataSetTableAdapters.OrdersTableAdapter();

// Set connection and transaction of TableAdapter to current connection and transaction (con,tr)
ordersAdapter.Connection = con;
ordersAdapter.Adapter.InsertCommand.Transaction
= ordersAdapter.Adapter.UpdateCommand.Transaction
= ordersAdapter.Adapter.DeleteCommand.Transaction
= ordersAdapter.Adapter.DeleteCommand.Transaction = tr;
ordersAdapter.Update(ds.Orders as TestDataSet.OrdersDataTable);
}
ds.Customers.AcceptChanges();
ds.Orders.AcceptChanges();
tr.Commit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
tr.Rollback();
}
finally
{
if (con.State != ConnectionState.Closed)
con.Close();
}
}
}
}

what about u ?
Is this code good ?
do u have idea to optimize this code ?
Thanks.