Thursday, October 14, 2004

Avoid Duplicate ADO.NET DataTable Events

Using ADO.NET DataSets, it's quite common to have some code like this:

dataset.datatable.Clear();
dataset.Merge(anotherDataset.datatable);


When your DataTable has some EventHandlers attached, e.g. due to DataBinding, those EventHandlers will be notified several times about value changes. Also, indices will be rebuild more than once and the like. This might result in a whole cascade of additional calls and lead to slow runtime performance.

This drawback can be avoided by batching two or more data manipulations using DataTable.BeginLoadData() / DataTable.EndLoadData():

try {
    dataset.datatable.BeginLoadData();
    dataset.datatable.Clear();
    dataset.Merge(anotherDataset.datatable);
}
finally {
    dataset.datatable.EndLoadData();
}


Another performance gain can be achieved by setting DataSet.EnforceConstraints to false (when not needed). This avoids constraint checks. In most of my .NET projects so far, it turned out to be better to let the database take care of constraint violations. Setting EnforceConstraints inside Visual Studio's XSD-Designer can be tricky. I didn't find the according property on the DataSet's property grid. But EnforceConstraints can be set manually within the XSD-file itself:

<xs:element name="MyDataSet" msdata:IsDataSet="true"
msdata:EnforceConstraints="False">


By the way, user interface controls bound to DataSets / DataTables resp. to IListSource-implementations are being repainted asynchronously on value changes in the underlying model. So luckily, several consecutive value changes lead to one repaint event only.