6.10. Checking for Concurrency Violations

Problem

You need to check for concurrency violations.

Solution

Use a timestamp column to manage data concurrency violations.

The schema of table TBL0610 used in this solution is shown in Table 6-12.

Table 6-12. TBL0610 schema

Column name

Data type

Length

Allow nulls?

Id

int

4

No

Field1

nvarchar

50

Yes

rowversion

timestamp

8

No

The sample code contains four event handlers and two methods:

Form.Load

Sets up the sample by creating two DataTable objects: A and B. For each, a DataAdapter is created and a handler is attached to handle the RowUpdated event. The DataAdapter is used to fill the DataTable with both schema and data from table TBL0610 in the database. The update command is defined for the DataAdapter using the timestamp column in the WHERE clause to catch concurrency errors. The first row from both tables is displayed on the form simulating the view of two different simultaneous data users.

DataAdapter.RowUpdated

Checks if the row was inserted or updated. For those rows, the current value of the timestamp column is retrieved from the TBL0610 in the database and used to update the row in the DataTable.

Update( )

This method copies the specified value for Field1 from the text box into the DataTable. The DataAdapter is used to update DataTable changes to table TBL0610 in the database. If a DBConcurrencyException is encountered, the change to the row is rejected.

DisplayRow( )

This method is used to display data from a specified row ...

Get ADO.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.