转至繁体中文版     | 网站首页 | 图文教程 | 资源下载 | 站长博客 | 图片素材 | 武汉seo | 武汉网站优化 | 
最新公告:     敏韬网|教学资源学习资料永久免费分享站!  [mintao  2008年9月2日]        
您现在的位置: 学习笔记 >> 图文教程 >> 站长学院 >> Web开发 >> 正文
Handling Data Concurrency Using ADO.NET         ★★★★

Handling Data Concurrency Using ADO.NET

作者:闵涛 文章来源:闵涛的学习笔记 点击数:2729 更新时间:2009/4/23 10:45:04
pdate the timestamp or datetime field''''s value back into the DataSet. If the same user wants to make more modifications, this updated value is reflected in the DataSet so it can be used again. There are a few different ways to do this. The fastest is using output parameters within the stored procedure. (This should only return if @@ROWCOUNT equals 1.) The next fastest involves selecting the row again after the UPDATE within the stored procedure. The slowest involves selecting the row from another SQL statement or stored procedure from the SqlDataAdapter''''s RowUpdated event.

I prefer to use the output parameter technique since it is the fastest and incurs the least overhead. Using the RowUpdated event works well, but it requires me to make a second call from the application to the database. The following code snippet adds an output parameter to the SqlCommand object that is used to update the Employee information:

oUpdCmd.Parameters.Add(new SqlParameter("@NewLastUpdateDateTime", 
  SqlDbType.DateTime, 8, ParameterDirection.Output, 
  false, 0, 0, "LastUpdateDateTime", DataRowVersion.Current, null));
oUpdCmd.UpdatedRowSource = UpdateRowSource.OutputParameters;

The output parameter has its sourcecolumn and sourceversion arguments set to point the output parameter''''s return value back to the current value of the LastUpdateDateTime column of the DataSet. This way the updated DATETIME value is retrieved and can be returned to the user''''s .aspx page.


Saving Changes

Now that the Employees table has the tracking field (LastUpdateDateTime) and the stored procedure has been created to use both the primary key and the tracking field in the WHERE clause of the UPDATE statement, let''''s take a look at the role of ADO.NET. In order to trap the event when the user changes the values in the textboxes, I created an event handler for the TextChanged event for each TextBox control:

private void txtLastName_TextChanged(object sender, System.EventArgs e)
{
    // Get the employee DataRow (there is only 1 row, otherwise I could
    // do a Find)
    dsEmployee.EmployeeRow oEmpRow =
           (dsEmployee.EmployeeRow)oDsEmployee.Employee.Rows[0];
    oEmpRow.LastName = txtLastName.Text;
    // Save changes back to Session
    Session["oDsEmployee"] = oDsEmployee;
}

This event retrieves the row and sets the appropriate field''''s value from the TextBox. (Another way of getting the changed values is to grab them when the user clicks the Save button.) Each TextChanged event executes after the Page_Load event fires on a postback, so assuming the user changed the first and last names, when the user clicks the Save button, the events could fire in this order: Page_Load, txtFirstName_TextChanged, txtLastName_TextChanged, and btnSave_Click.

The Page_Load event grabs the row from the DataSet in the Session object; the TextChanged events update the DataRow with the new values; and the btnSave_Click event attempts to save the record to the database. The btnSave_Click event calls the SaveEmployee method (shown in Figure 3) and passes it a bLastInWins value of false since we want to attempt a standard save first. If the SaveEmployee method detects that changes were made to the row (using the HasChanges method on the DataSet, or alternatively using the RowState property on the row), it creates an instance of the Employee class and passes the DataSet to its SaveEmployee method. The Employee class could live in a logical or physical middle tier. (I wanted to make this a separate class so it would be easy to pull the code out and separate it from the presentation logic.)

Notice that I did not use the GetChanges method to pull out only the modified rows and pass them to the Employee object''''s Save method. I skipped this step here since there is only one row. However, if there were multiple rows in the DataSet''''s DataTable, it would be better to use the GetChanges method to create a DataSet that contains only the modified rows.

If the save succeeds, the Employee.SaveEmployee method returns a DataSet containing the modified row and its newly updated row version flag (in this case, the LastUpdateDateTime field''''s value). This DataSet is then merged into the original DataSet so that the LastUpdateDateTime field''''s value can be updated in the original DataSet. This must be done because if the user wants to make more changes she will need the current values from the database merged back into the local DataSet and shown on screen. This includes the LastUpdateDateTime value which is used in the WHERE clause. Without this field''''s current value, a false concurrency violation would occur.


Reporting Violations

If a concurrency violation occurs, it will bubble up and be caught by the exception handler shown in Figure 3 in the catch block for DBConcurrencyException. This block calls the FillConcurrencyValues method, which displays both the original values in the DataSet that were attempted to be saved to the database and the values currently in the database. This method is used merely to show the user why the violation occurred. Notice that the exDBC variable is passed to the FillConcurrencyValues method. This instance of the special database concurrency exception class (DBConcurrencyException) contains the row where the violation occurred. When a concurrency violation occurs, the screen is updated to look like Figure 1.

The DataSet not only stores the schema and the current data, it also tracks changes that have been made to its data. It knows which rows and columns have been modified and it keeps track of the before and after versions of these values. When accessing a column''''s value via the DataRow''''s indexer, in addition to the column index you can also specify a value using the DataRowVersion enumerator. For example, after a user changes the value of the last name of an employee, the following lines of C# code will retrieve the original and current values stored in the LastName column:

string sLastName_Before = oEmpRow["LastName", DataRowVersion.Original];
string sLastName_After = oEmpRow["LastName", DataRowVersion.Current];

The FillConcurrencyValues method uses the row from the DBConcurrencyException and gets a fresh copy of the same row from the database. It then displays the values using the DataRowVersion enumerators to show the original value of the row before the update and the value in the database alongside the current values in the textboxes.


User''''s Choice

Once the user has been notified of the concurrency issue, you could leave it up to her to decide how to handle it. Another alternative is to code a specific way to deal with concurrency, such as always handling the exception to let the user know (but refreshing the data from the database). In this sample application I let the user decide what to do next. She can either cancel changes, cancel and reload from the database, save changes, or save anyway.

The option to cancel changes simply calls the RejectChanges method of the DataSet and rebinds the DataSet to the controls in the ASP.NET page. The RejectChanges method reverts the changes that the user made back to its original state by setting all of the current field values to the original field values. The option to cancel changes and reload the data from the database also rejects the changes but additionally goes back to the database via the Employee class in order to get a fresh copy of the data before rebinding to the control on the ASP.NET page.

The option to save changes attempts to save the changes but will fail if a concurrency violation is encountered. Finally, I included a "save anyway" option. This option takes the values the user attempted to save and uses the last-in wins technique, overwriting whatever is in the database. It does this by calling a different command object associated with a stored procedure that only uses the primary key field (EmployeeID) in the WHERE clause of the UPDATE statement. This technique should be used with caution as it will overwrite the record.

If you want a more automatic way of dealing with the changes, you could get a fresh copy from the database. Then overwrite just the fields that the current user modified, such as the Extension field. That way, in the example I used the proper LastName would not be overwritten. Use this with caution as well, however, because if the same field was modified by both users, you may want to just back out or ask the user what to do next. What is obvious here is that there are several ways to deal with concurrency violations, each of which must be carefully weighed before you decide on the one you will use in your application.


Wrapping It Up

Setting the SqlDataAdapter''''s ContinueUpdateOnError property tells the SqlDataAdapter to either throw an exception when a concurrency violation occurs or to skip the row that caused the violation and to continue with the remaining updates. By setting this property to false (its default value), it will throw an exception when it encounters a concurrency violation. This technique is ideal when only saving a single row or when you are attempting to save multiple rows and want them all to commit or all to fail.

I have split the topic of concurrency violation management into two parts. Next time I will focus on what to do when multiple rows could cause concurrency violations. I will also discuss how the DataViewRowState enumerators can be used to show what changes have been made to a DataSet.


Send your questions and comments for John to  mmdata@microsoft.com.

John Papa  is a baseball fanatic who spends most of his summer nights rooting for the Yankees with his two little girls, wife, and faithful dog, Kadi. He has authored several books on ADO, XML, a

上一页  [1] [2] [3]  下一页


[办公软件]GETPIVOTDATA函数语法介绍  [系统软件]Using dllimport and dllexport in C++ Classes
[常用软件]桌面搜索新利器 “88Data”  [VB.NET程序]VB.NET Data Types
[VB.NET程序]如何用VB实现QBASIC中的data数据的read  [VB.NET程序]How to setup a basic Struts project using Ecli…
[VB.NET程序]Event-Handling Basics  [Web开发]Ajax using XMLHttpRequest and Struts
[Web开发]Using Windows Forms Controls in Internet Explo…  [Web开发]ADO在MICROSOFT DATA ACCESS 中的角色
教程录入:mintao    责任编辑:mintao 
  • 上一篇教程:

  • 下一篇教程:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
      注:本站部分文章源于互联网,版权归原作者所有!如有侵权,请原作者与本站联系,本站将立即删除! 本站文章除特别注明外均可转载,但需注明出处! [MinTao学以致用网]
      网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)

    同类栏目
    · Web开发  · 网页制作
    · 平面设计  · 网站运营
    · 网站推广  · 搜索优化
    · 建站心得  · 站长故事
    · 互联动态
    更多内容
    热门推荐 更多内容
  • 没有教程
  • 赞助链接
    更多内容
    闵涛博文 更多关于武汉SEO的内容
    500 - 内部服务器错误。

    500 - 内部服务器错误。

    您查找的资源存在问题,因而无法显示。

    | 设为首页 |加入收藏 | 联系站长 | 友情链接 | 版权申明 | 广告服务
    MinTao学以致用网

    Copyright @ 2007-2012 敏韬网(敏而好学,文韬武略--MinTao.Net)(学习笔记) Inc All Rights Reserved.
    闵涛 投放广告、内容合作请Q我! E_mail:admin@mintao.net(欢迎提供学习资源)

    站长:MinTao ICP备案号:鄂ICP备11006601号-18

    闵涛站盟:医药大全-武穴网A打造BCD……
    咸宁网络警察报警平台