ADO - Entity Tracking and Change Detection in DataSets
Entity tracking and change detection are important mechanisms in ADO.NET DataSets that help applications monitor modifications made to data after it has been loaded from a database. These features are especially useful in disconnected architectures where data is retrieved, manipulated locally, and later synchronized back to the database.
A DataSet acts as an in-memory cache of data. Once records are loaded into a DataSet, users or applications can insert, update, or delete rows without maintaining a constant database connection. To properly update the database later, ADO.NET needs to know which rows were modified and what changes occurred. This is achieved through entity tracking and change detection.
Understanding Entity Tracking
Entity tracking refers to the process of monitoring the state of rows and data entities inside a DataSet. Each row in a DataTable maintains information about its current state.
ADO.NET automatically tracks the status of every DataRow using the RowState property.
The possible row states are:
| RowState Value | Description |
|---|---|
| Added | A new row has been added |
| Modified | An existing row has been changed |
| Deleted | A row has been marked for deletion |
| Unchanged | The row has not changed since loading or accepting changes |
| Detached | The row is not part of any DataTable |
This tracking allows the DataAdapter object to determine what SQL operations should be executed during database updates.
Example of RowState Tracking
using System;
using System.Data;
class Program
{
static void Main()
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
DataRow row = table.NewRow();
row["ID"] = 1;
row["Name"] = "Rahul";
table.Rows.Add(row);
Console.WriteLine(row.RowState);
}
}
Output:
Added
The row state becomes Added because the row was newly inserted into the DataTable.
Change Detection in DataSets
Change detection identifies modifications made to data after it is loaded. ADO.NET compares original values and current values to detect changes.
Each DataRow stores multiple versions of data:
| Version | Description |
|---|---|
| Original | The value when data was first loaded |
| Current | The latest modified value |
| Proposed | Temporary value during editing |
| Default | Default version based on row state |
This multi-version storage enables accurate tracking of modifications.
Example of Detecting Modified Data
using System;
using System.Data;
class Program
{
static void Main()
{
DataTable table = new DataTable();
table.Columns.Add("Name");
DataRow row = table.NewRow();
row["Name"] = "Amit";
table.Rows.Add(row);
table.AcceptChanges();
row["Name"] = "Vikram";
Console.WriteLine(row.RowState);
}
}
Output:
Modified
Initially, the row becomes Added. After calling AcceptChanges(), the state changes to Unchanged. When the value is edited again, the row state becomes Modified.
Role of AcceptChanges()
The AcceptChanges() method commits all changes inside the DataSet or DataTable.
Effects of AcceptChanges():
-
Added rows become Unchanged
-
Modified rows become Unchanged
-
Deleted rows are permanently removed
-
Original values are updated with current values
Example:
table.AcceptChanges();
This method is commonly used after successfully updating the database.
RejectChanges() Method
RejectChanges() cancels all modifications and restores original values.
Example:
row["Name"] = "Kiran";
row.RejectChanges();
After rejection, the row returns to its previous value.
This feature is useful when users cancel editing operations.
Using GetChanges()
The GetChanges() method extracts only modified rows from a DataSet.
Example:
DataSet changedData = ds.GetChanges();
This improves performance because only changed records are processed during updates.
The method can also filter changes by row state.
Example:
DataSet modifiedRows = ds.GetChanges(DataRowState.Modified);
DataAdapter and Change Tracking
The DataAdapter uses row state information to perform corresponding database operations.
| Row State | SQL Operation |
|---|---|
| Added | INSERT |
| Modified | UPDATE |
| Deleted | DELETE |
When Update() is called, the DataAdapter scans row states and executes appropriate commands.
Example:
adapter.Update(ds, "Employees");
Optimistic Concurrency and Change Detection
ADO.NET commonly uses optimistic concurrency control.
In optimistic concurrency:
-
Multiple users can edit data simultaneously
-
Conflicts are checked only during updates
-
Original values are compared with database values
If another user changes the same row before update, a concurrency conflict may occur.
Example workflow:
-
User A loads data
-
User B modifies the same row
-
User A attempts update
-
ADO.NET detects mismatch
-
Conflict handling occurs
This helps prevent accidental overwriting of data.
Tracking Deleted Rows
Deleted rows are not immediately removed from memory.
Instead, they are marked with Deleted state.
Example:
row.Delete();
Console.WriteLine(row.RowState);
Output:
Deleted
The row remains available until AcceptChanges() is called.
RowVersion Usage
The DataRowVersion enumeration helps access different versions of data.
Example:
Console.WriteLine(row["Name", DataRowVersion.Original]);
Console.WriteLine(row["Name", DataRowVersion.Current]);
This is valuable for auditing, concurrency control, and rollback operations.
Advantages of Entity Tracking and Change Detection
Efficient Database Updates
Only modified rows are updated, reducing unnecessary database operations.
Disconnected Data Management
Applications can work offline and synchronize later.
Improved Performance
Tracking minimizes network traffic and server load.
Better Concurrency Handling
Changes from multiple users can be managed safely.
Undo and Rollback Support
Original values can be restored when needed.
Limitations
Increased Memory Usage
Multiple row versions consume additional memory.
Complexity in Large Applications
Managing state changes becomes complicated with many tables.
Concurrency Conflicts
Simultaneous edits may require manual conflict resolution.
Real-World Applications
Banking Systems
Track transaction changes before committing updates.
Inventory Management
Monitor stock updates from multiple users.
Offline Desktop Applications
Allow local editing and later synchronization.
Enterprise Reporting Systems
Detect modifications before generating reports.
Conclusion
Entity tracking and change detection are core features of ADO.NET DataSets that enable efficient disconnected data handling. By maintaining row states and multiple data versions, ADO.NET can accurately identify inserts, updates, and deletions. These mechanisms improve performance, support concurrency control, and simplify database synchronization in enterprise applications.