当前位置: 移动技术网 > IT编程>开发语言>.net > 在ASP.NET 2.0中操作数据之六十一:在事务里对数据库修改进行封装

在ASP.NET 2.0中操作数据之六十一:在事务里对数据库修改进行封装

2017年12月12日  | 移动技术网IT编程  | 我要评论

乔布斯传txt下载,杜罗西,丰城网络

导言:

  正如我们在第16章《》里探讨的那样,gridview控件内建的功能支持对每行数据的编辑和删除功能,你只需要稍稍动一下鼠标就可以创建丰富的数据修改界面而不用写一行代码.但是,在某些情况下,这还不够,我们需要让用户能够成批地处理数据.

  比如,很多基于web(web-based)的电子邮件客户端,将所有邮件出来,每条邮件除了包含邮件信息(主题、发送者等)外,还包含一个checkbox控件。这些界面允许用户同时删除多个邮件,用户只需要选中邮件,再点"删除所选邮件"按钮.当用户要编辑多条不同的记录的时候,提供一个批编辑界面是比较理想的.我们用不着让用户每次都选中一条要编辑的记录,再做相关的修改,最后点“更新”按钮,在批编辑界面里每条记录都有各自的编辑选项,用户可以快速地编辑多条记录再点“update all”按钮来保存对他们所做的修改.本系列我们将考察如何创建对数据进行添加、编辑、删除批处理的界面.

  如果想对批处理执行atomic operation(原子操作), 那么首先,所做的操作要么都执行成功要么都失败,另外还要对数据访问层进行扩充以支持database transactions(数据库事务)。数据库事务确保insert, update, 和 delete语句执行的atomicity(原子数)置于数据库事务的保护之下.另外,绝大多数的当代数据库系统都支持数据库事务.

  在本系列我们先看如何扩充数据访问层以支持数据库事务,接下来我们看如何创建页面以包含添加、更新、删除数据的批处理界面,让我们开始吧.

  注意:在批处理事务里修改数据时,原子数(atomicity)并非总数必要的。在批处理的某些情况下,某些修改成功某些修改失败是可以接受的。比如删除电子邮件时,有些邮件在删除过程中发生了数据库错误,有些邮件没有发生错误,对这种没有发生错误的邮件,批处理照样将其删除掉.对这种情况,我们没有必要设置数据访问层dal支持数据库事务.不过在其它某些情况下,原子数是至关重要的.比如某个客户想把资金从一个银行帐户转移到另一个银行帐号,下面2个操作必须执行成功:首先,将第一个帐号的资金扣除,然后将资金转入第二个帐号.如果第一步执行成功,第二步执行失败,银行当然高兴,客户怕是要发疯了.在后面的文章里我们将创建添加、更新、删除的批处理界面,就算你不打算在这些页面里使用数据库事务,我也希望你照着本篇文章,对数据访问层进行扩展一支持数据库事务.

事务概述

绝大多数的数据库都支持事务,它可以将多个数据库命令当成一个逻辑单位进行处理.这些包含事务的命令要么都执行成功要么都执行失败.

一般来说,事务通过sql命令来执行,使用如下的模式:

1.声明事务开始
2.执行构成事务的那些sql命令
3.如果在第二步中的任何一个命令出错,执行事务回滚(rollback the transaction)
4.如果在第二步中的所有命令成功执行,提交事务

  这些sql命令可以通过手写的方式输入,比如写sql脚本、创建存储过程、也可以通过编程的方式来构建,比如使用ado.net技术或调用system.transactions namespace命名空间的类.在本文,我们仅仅考察用ado.net技术管理事务.在后面的教程我们看如何在数据访问层data access layer里使用存储过程,到那时,我们再来考察这些创建、回滚、提交事物的sql命令。另外,要获得更多信息请参考文章《managing transactions in sql server stored procedures》()

  注意:system.transactions namespace命名空间的transactionscope class类允许开发者通过编程的方式获取事务里的一系列命令,且允许事务包含多个数据源,甚至类型不同,比如:microsoft sql server database, 或oracle database,甚至web service.本教程我们使用ado.net技术而非transactionscope class类,是因为ado.net指定数据库事务更详细,且在很多情况下占用资源更少.此外,在某些情况下,transactionscope class类要用到microsoft distributed transaction coordinator (msdtc),围绕msdtc的配置、执行和性能问题是比较专业、高级的问题稍微超出了本教程的范围.

  在ado.net里,通过调用sqlconnection class类的begintransaction method方法启动事务, 该方法返回一个sqltransaction object对象.将构成事务的数据操作命令放在try...catch区域,如果在try区域的某个命令出错的话,程序将转到catch区域,在此,通过sqltransaction object对象的rollback method方法执行事务回滚。如果所有的命令执行成功,将调用位于try区域底部的sqltransaction object对象的commit method方法来提交事务.下面的代码片段揭示了该模式。要想看在ado.net里使用事务的更多例子,请参阅文章《maintaining database consistency with transactions》().

// create the sqltransaction object
sqltransaction mytransaction = sqlconnectionobject.begintransaction();

try
{
 /*
 * ... perform the database transaction's data modification statements...
 */

 // if we reach here, no errors, so commit the transaction
 mytransaction.commit();
}
catch
{
 // if we reach here, there was an error, so rollback the transaction
 mytransaction.rollback();

 throw;
}

  默认情况下,强类型数据集(typed dataset)里的tableadapters并不使用事务。为此,我们要对tableadapter classes类进行扩展,以包含额外的方法以使用上述模式来执行事务。在第二步,我们看如何使用一个partial classes类来添加这些方法.

第一步:创建批处理数据的页面

  在我们考察如何扩展数据访问层dal以支持数据库事务之前,让我们花点时间来创建一些asp.net web页面,我们在本章及后面三章将用到它们.

添加一个名为batchdata的新文件夹,再添加如下的 asp.net页面, 务必套用site.master模板页.

default.aspx
transactions.aspx
batchupdate.aspx
batchdelete.aspx
batchinsert.aspx

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908164701.jpg
图1:添加相关的页面

就像其它文件夹里的default.aspx页面一样,用sectionleveltutoriallisting.ascx用户控件来列出本部分的章节。将其从解决资源管理器里拖到default.aspx页面.

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908162316.jpg
图2:将sectionleveltutoriallisting.ascx用户控件添加到default.aspx页面

最后添加如下代码到web.sitemap文件,具体的,将其添加到“customizing the site map” <sitemapnode>后面:

<sitemapnode title="working with batched data"
 url="~/batchdata/default.aspx"
 description="learn how to perform batch operations as opposed to
  per-row operations.">
 
 <sitemapnode title="adding support for transactions"
 url="~/batchdata/transactions.aspx"
 description="see how to extend the data access layer to support
  database transactions." />
 <sitemapnode title="batch updating"
 url="~/batchdata/batchupdate.aspx"
 description="build a batch updating interface, where each row in a
  gridview is editable." />
 <sitemapnode title="batch deleting"
 url="~/batchdata/batchdelete.aspx"
 description="explore how to create an interface for batch deleting
  by adding a checkbox to each gridview row." />
 <sitemapnode title="batch inserting"
 url="~/batchdata/batchinsert.aspx"
 description="examine the steps needed to create a batch inserting
  interface, where multiple records can be created at the
  click of a button." />
</sitemapnode>

完成后,花几分钟在浏览器里登录页面,左面的菜单列出了本部分的各项

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908176830.jpg
图3:site map现在包含了本章节

第二步:更新数据访问层以支持数据库事务

  就像我们在第一章《》探讨的一样,位于数据访问层的强类型数据集(typed dataset)由datatables 和 tableadapters构成.  datatables保存数据,而tableadapters提供相应的方法从数据库读取数据,并根据datatables的改动对数据库做相应的更新,等等.记得tableadapters有2种更新数据的模式——batch update 和 db-direct.就batch update模式而言, tableadapter可以传入dataset, datatable, 或datarows集,遍历这些数据对要添加、修改、删除的行执行相应的insertcommand, updatecommand, or deletecommand方法。就db-direct模式而言,tableadapter传入的是那些需要进行添加、更新、删除操作的某条记录的列的值,再使用这些值执行相关的insertcommand, updatecommand, 或deletecommand命令.

  tableadapter自动生成的方法并不使用事务.默认状态下,tableadapter执行的每一个insert, update, 或delete操作都看作是单独的、互不相干的.假定在业务逻辑层bll里使用db-direct模式来向数据库添加十条记录,代码将分十次调用tableadapter的insert方法. 如果前5条记录添加正常,而在添加第六条记录时发生异常,前5条记录仍然保存在数据库.同样的,用batch update模式来操作的话,效果亦然.

  在某些情况下,我们想确保在进行一系列的改动时引入原子数(atomicity).为此,我们必须手动扩展tableadapter,通过添加一些新的方法将insertcommand, updatecommand, 和deletecommands命令置于事务之下.在第一章《》里,我们考察了使用部分类(partial classes)对强类型数据集(typed dataset)里的datatable的函数进行扩充.该技术同样适用于tableadapter.

  强类型数据集northwind.xsd位于app_code文件夹的dal子文件夹里.在dal文件夹里再创建一个名为transactionsupport的子文件夹,再在里面添加一个新类,名为productstableadapter.transactionsupport.cs (见图4).该类包含productstableadapter的使用事务的方法.

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908172346.jpg
图4:创建一个名为transactionsupport的新文件夹并添加一个名为productstableadapter.transactionsupport.cs的新类

在productstableadapter.transactionsupport.cs文件里键入如下的代码:

using system;
using system.data;
using system.data.sqlclient;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;

namespace northwindtableadapters
{
 public partial class productstableadapter
 {
 private sqltransaction _transaction;
 private sqltransaction transaction
 {
 get
 { 
 return this._transaction;
 }
 set
 {
 this._transaction = value;
 }
 }


 public void begintransaction()
 {
 // open the connection, if needed
 if (this.connection.state != connectionstate.open)
 this.connection.open();

 // create the transaction and assign it to the transaction property
 this.transaction = this.connection.begintransaction();

 // attach the transaction to the adapters
 foreach (sqlcommand command in this.commandcollection)
 {
 command.transaction = this.transaction;
 }

 this.adapter.insertcommand.transaction = this.transaction;
 this.adapter.updatecommand.transaction = this.transaction;
 this.adapter.deletecommand.transaction = this.transaction;
 }


 public void committransaction()
 {
 // commit the transaction
 this.transaction.commit();

 // close the connection
 this.connection.close();
 }


 public void rollbacktransaction()
 {
 // rollback the transaction
 this.transaction.rollback();

 // close the connection
 this.connection.close();
 }
 }
}

  类声明里的关键字partial向编译器表明代码里添加的成员(members)是添加到命名空间northwindtableadapters里的productstableadapter class类.我们注意到在文件的顶部有一个using system.data.sqlclient声明,这是因为tableadapter被设置为使用sqlclient provider,在其内部使用一个sqldataadapter object对象来向数据库发出命令.因此,我们需要使用sqltransaction class类来启动事务,然后提交或回滚事务.如果没有使用microsoft sql server数据库的话,你需要调用恰当的provider.

  这些方法被标记为public,我们可以在productstableadapter里,或数据访问层dal的其它类,甚至是其它层比如业务逻辑层bll来调用这些法.
begintransaction()方法打开了tableadapter的内部的sqlconnection(如果需要的话), 开启事务并赋值给transaction属性,并将事务分配(attache)给sqldataadapter的sqlcommand objects对象.committransaction()和 rollbacktransaction()方法在关闭内部的connection object对象前分别调用transaction object对象的commit 和 rollback方法.

  添加上述代码后,我们将在productsdatatable 或业务逻辑层bll里添加方法以执行一系列的置于事务之下的命令. 下面的代码在batch update pattern模式里使用一个事务来更新一个productsdatatable instance实例.它调用begintransaction method方法来启动一个事务,然后用一个try...catch模块来发布数据更改命令.如果调用adapter object对象的update方法出现异常,那么将转到catch区域,对事务进行回滚.记得执行batch update pattern模式的update方法将遍历productsdatatable里的所有行(rows),执行相应的insertcommand, updatecommand, 和deletecommands命令.如果这些命令中的其中一个出现异常,事务将回滚,撤销在事务里的所做的更改.如果update命令全部执行无异常,那么提交事务.

public int updatewithtransaction(northwind.productsdatatable datatable)
{
 this.begintransaction();

 try
 {
 // perform the update on the datatable
 int returnvalue = this.adapter.update(datatable);

 // if we reach here, no errors, so commit the transaction
 this.committransaction();

 return returnvalue;
 }
 catch
 {
 // if we reach here, there was an error, so rollback the transaction
 this.rollbacktransaction();

 throw;
 }
}

  将上述的updatewithtransaction()方法添加到文件productstableadapter.transactionsupport.cs里的productstableadapter class类。另外,还可以将该方法添加到业务逻辑层的productsbll class类,不过要做些许修改:即将this.begintransaction(), this.committransaction(), and this.rollbacktransaction()三中方法里的关键字“this”替换为“adapter”(我们知道,productsbll类里的productstableadapter的name属性即是adapter).

  updatewithtransaction()方法使用的是batch update模式,不过也可在事务里调用db-direct模式,就像下面的代码显示的那样.deleteproductswithtransaction()方法接受一个int类型的list<t>,也就是要删除的productids.该方法通过调用begintransaction来启动事务,然后在try模块里对每一个productid值调用db-direct模式的delete方法.如果任何一个对delete的调用出错,将转到catch 模块,事务将会回滚;如果所有对delete的调用成功,那就提交事务。添加该方法给productsbll class类.

public void deleteproductswithtransaction
 (system.collections.generic.list<int> productids)
{
 // start the transaction
 adapter.begintransaction();

 try
 {
 // delete each product specified in the list
 foreach (int productid in productids)
 {
 adapter.delete(productid);
 }

 // commit the transaction
 adapter.committransaction();
 }
 catch
 {
 // there was an error - rollback the transaction
 adapter.rollbacktransaction();

 throw;
 }
}

在多个tableadapters应用事务

  到目前为止我们考察的是对productstableadapter里的多个命令采用原子操作.如果我们是对多个不同的数据库表进行改动,并对这些改动执行原子操作那又怎么办呢?比如:当删除一个category时,在删除之前我们想把该种类对应的products分配给其它的category.对这种2步操作——分配products和删除category——应该执行原子操作.但是productstableadapter只包含修改products表的方法;而categoriestableadapter只包含修改categories表的方法.那么怎样使用一个包含这2个tableadapters的事务呢?

  其中一个办法是向categoriestableadapter添加一个名为deletecategoryandreassignproducts(categoryidtodelete, reassigntocategoryid)的方法.再定义一个方法来调用一个存储过程,使用事务来达到分配products和删除category的目的.我们将在后面考察在一个存储过程里开始、提交和回滚事务.

  另一个方法是在数据访问层里添加一个类,来包含deletecategoryandreassignproducts(categoryidtodelete, reassigntocategoryid)方法.该方法创建categoriestableadapter 和 the productstableadapter的实例,并将这2个tableadapters的connection属性设置为相同的sqlconnection实例。这样,它们都将调用begintransaction来开启事务.然后在try...catch模块里执行分配products和删除category的方法,最后提交或回滚事务.

第四步:向业务逻辑层添加updatewithtransaction方法

  在第三步我们向数据访问层dal里的productstableadapter添加了一个updatewithtransaction方法,我们将向业务逻辑层添加相应的方法.虽然表现层可以直接向dal调用updatewithtransaction方法,但是我们在这里仍然将它们分隔开。

  打开productsbll class类,添加一个名为updatewithtransaction的方法,该方法仅仅简单地调用对应的dal方法.现在productsbll类里有2个方法:updatewithtransaction方法——我们才添加的;以及deleteproductswithtransaction——我们在第三步添加的.

public int updatewithtransaction(northwind.productsdatatable products)
{
 return adapter.updatewithtransaction(products);
}


public void deleteproductswithtransaction
 (system.collections.generic.list<int> productids)
{
 // start the transaction
 adapter.begintransaction();

 try
 {
 // delete each product specified in the list
 foreach (int productid in productids)
 adapter.delete(productid);

 // commit the transaction
 adapter.committransaction();
 }
 catch
 {
 // there was an error - rollback the transaction
 adapter.rollbacktransaction();

 throw;
 }
}

  注意:根productsbll类里的大部分方法不同,上述方法并不包含dataobjectmethodattribute属性。这是因为我们将直接在asp.net页面的后台代码里调用这些方法,记得dataobjectmethodattribute方法的作用是指出哪些方法应该出现在objectdatasource控件的设置数据源向导的某些标签(select, update, insert, 或delete)里.由于gridview控件缺乏内置的支持“批编辑”或“批删除”的功能,我们将通过编辑的方式来调用这些方法.

第五步:在表现层更新数据库数据

  为演示更新一批记录时事务的作用,我们将创建一个用户界面来将所有产品用一个gridview控件显示出来,并包含一个button web控件。当点击该按钮时为product重新赋值一个有效的categoryid值。具体来说,对头几个products分配一个有效的categoryid值;而剩下的分配一个无效的(non-existent)categoryid值,当我们试图对这样的一个product——其categoryid值与现有的category的categoryid不匹配——进行更新时,将违反外键约束,进而抛出一个异常.在本文的示例里你将看到,在使用事务时,当违反外键约束抛出一个异常时将导致前面的正确分配categoryid值的操作产生回滚.如果不使用事务的话,这些正确的操作将执行成功.

  首先,打开batchdata文件夹里的transactions.aspx页面,从工具箱拖一个gridview控件到页面。设置其id为products,从其智能标签里将其绑定到一个名为productsdatasource的objectdatasource控件,设置该控件调用productsbll class类的getproducts()方法。由于该gridview是“只读”的,在update, insert, 和delete标签里选“(none)”,点完成。

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908171875.jpg
图5:设置objectdatasource使用productsbll class类的getproducts方法

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908175701.jpg
图6:在update, insert, 和delete标签里选“(none)”

  完成设置后,visual studio将自动的添加boundfields以及一个checkboxfield,删除productid, productname, categoryid,和categoryname以外的其它列;并且分别将productname 和 categoryname列的headertext属性重命名为“product” 和 “category”.在智能标签里启用“分页”功能.做完这些修改后,gridview 和 objectdatasource控件的声明代码看起来应该和下面的差不多:

<asp:gridview id="products" runat="server" allowpaging="true"
 autogeneratecolumns="false" datakeynames="productid"
 datasourceid="productsdatasource">
 <columns>
 <asp:boundfield datafield="productid" headertext="productid"
 insertvisible="false" readonly="true"
 sortexpression="productid" />
 <asp:boundfield datafield="productname" headertext="product"
 sortexpression="productname" />
 <asp:boundfield datafield="categoryid" headertext="categoryid"
 sortexpression="categoryid" />
 <asp:boundfield datafield="categoryname" headertext="category"
 sortexpression="categoryname" />
 </columns>
</asp:gridview>

<asp:objectdatasource id="productsdatasource" runat="server"
 oldvaluesparameterformatstring="original_{0}"
 selectmethod="getproducts" typename="productsbll">
</asp:objectdatasource>

  然后,在gridview控件上添加3个button web控件,设置第一个按钮的text属性 为“refresh grid”;第二个按钮的text属性为“modify categories (with transaction)”;第三个按钮的text属性为“modify categories (without transaction)”.

 

<p>
 <asp:button id="refreshgrid" runat="server" text="refresh grid" />
</p>
<p>
 <asp:button id="modifycategorieswithtransaction" runat="server"
 text="modify categories (with transaction)" />
</p>
<p>
 <asp:button id="modifycategorieswithouttransaction" runat="server"
 text="modify categories (without transaction)" />
</p>


此时,在visual studio的设计模式里,界面看起来和下面的截屏差不多:

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908178459.jpg
图7:页面包含一个gridview控件和三个button web控件

为这3个按钮的click events事件创建事件处理器,如下:

protected void refreshgrid_click(object sender, eventargs e)
{
 products.databind();
}

protected void modifycategorieswithtransaction_click(object sender, eventargs e)
{
 // get the set of products
 productsbll productsapi = new productsbll();
 northwind.productsdatatable products = productsapi.getproducts();

 // update each product's categoryid
 foreach (northwind.productsrow product in products)
 {
 product.categoryid = product.productid;
 }

 // update the data using a transaction
 productsapi.updatewithtransaction(products);

 // refresh the grid
 products.databind();
}

protected void modifycategorieswithouttransaction_click(object sender, eventargs e)
{
 // get the set of products
 productsbll productsapi = new productsbll();
 northwind.productsdatatable products = productsapi.getproducts();

 // update each product's categoryid
 foreach (northwind.productsrow product in products)
 {
 product.categoryid = product.productid;
 }

 // update the data without using a transaction
 northwindtableadapters.productstableadapter productsadapter =
 new northwindtableadapters.productstableadapter();
 productsadapter.update(products);

 // refresh the grid
 products.databind();
}

 

  refresh按钮的click事件处理器仅仅调用products gridview的databind方法将数据重新绑定到ridview控件.

  第二个事件处理器对products的categoryid属性重新赋值,并调用bll层里的新的事务方法来执行数据库更新.我们注意到将每个产品的productid值赋给其categoryid属性,对最开头的几个产品而言没有任何问题,但随着productid值越变越大,categoryid的值也越变越大,而category表里定义的种类毕竟有限,于是问题就出来了。

  第三个事件处理器也是将productid值赋给categoryid属性,只是用productstableadapter的默认的update方法来更新数据库. 该update方法并没有使用事务来封装这些命令,所以只要是没有违背外键约束的更新都会执行成功.

  在浏览器里登录该页面进行验证.最开始你将看到如图8所示的画面,然后点“modify categories (with transaction)”.这将导致页面回传并试题更新所有products的categoryid值,这将导致违背外键约束(见图9).

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908187988.jpg
图8:products将显示在一个分页的gridview控件里

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908187517.jpg
图9:导致违背外键约束

  现在点击浏览器的back按钮,再点击“refresh grid”按钮,此时你看到的界面和图8的界面一摸一样。这是因为发生了违背外键约束,导致回滚,所有的操作失败.

  再点“modify categories (without transaction)”按钮,这同样将违背外键约束(见图9),不过这一次,那些对categoryid属性赋以有效值的操作不会回滚.点击浏览器的back按钮,再点“refresh grid”按钮。就像图10显示的那样,最开始的8个产品的categoryid值已经发生了更改,比如,在图8里chang的categoryid值为1,而在图10里就变成了2了.

http://www.lhsxpumps.com/_images/10qianwan/20171212/b_1_201712121908186075.jpg
图10:某些product的categoryid值发生了改变,而其它的没有

结语:

  默认情况下,tableadapter的方法没有使用事务来执行数据库命令,不过只需多做一点工作我们就可以添加一些用于创建、提交、回滚事务的方法.在本教程,我们在productstableadapter class类里创建了这3个方法:begintransaction, committransaction,和rollbacktransaction.我们考察了如何在try...catch模块里使用这些方法来执行一系列的修改命令.具体来说,我们在productstableadapter里创建了updatewithtransaction方法,该方法运用batch update模式对productsdatatable里的每行记录执行必要的更改操作;我们也对bll里的productsbll class类添加了deleteproductswithtransaction方法,它将一系列productid值作为输入参数,并使用db-direct模式将每个产品删除.这些方法开始都创建一个事务,再在try...catch模块里执行数据更改命令.如果抛出异常,则回滚事务,否则提交事务.

  第五步演示了事务的作用。在接下来的3章我们将以本章为基础,创建批更新、批删除、批添加的用户界面.

  祝编程快乐!

作者简介

  本系列教程作者 scott mitchell,著有六本asp/asp.net方面的书,是4guysfromrolla.com的创始人,自1998年以来一直应用 微软web技术。大家可以点击查看全部教程《[翻译]scott mitchell 的asp.net 2.0数据教程》,希望对大家的学习asp.net有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网