How to implement static data sources in web pages to avoid hitting the database on every postback?
Sometimes, when developing Web applications with ASP.NET, you may require to use a small amount of data repeatedly throughout the life of the application and further, such data is shared among users accessing your application.
Let's say a dataset created in designer points to the DataSetCustomers schema.
C#
//Defining object for the existing dataset
private static Namespace.DataSetCustomers dataSet11 = null;
// Initializing a static datasource based on the datasource created in the designer.
public static Namespace.DataSetCustomers GetDataSet(System.Data.OleDb.OleDbDataAdapter adapter, Namespace.DataSetCustomers defaultDataSet)
{
if(dataSet11 == null)
{
dataSet11 = new Namespace.DataSetCustomers();
((System.ComponentModel.ISupportInitialize)(dataSet11)).BeginInit();
dataSet11.DataSetName = defaultDataSet.DataSetName;
dataSet11.EnforceConstraints = defaultDataSet.EnforceConstraints;
dataSet11.Locale = defaultDataSet.Locale;
((System.ComponentModel.ISupportInitialize)(dataSet11)).EndInit();
adapter.Fill(dataSet11);
}
return dataSet11;
}
#endregion
//Filling a DataAdapter using static datasource. Instead of filling a DataAdapter with the dataset created in the designer, you can use the static data source.
//this.oleDbDataAdapter1.Fill(this.dataSetCustomers1);
//Using a static datasource, changes made to the dataset will be preserved across postback.
this.dataSetCustomers1 = GetDataSet(this.oleDbDataAdapter1, this.dataSetCustomers1);
VB
'Defining object for the existing dataset
Private Shared dataSet11 As Namespace.DataSetCustomers = Nothing
' Initializing a static datasource based on the datasource created in the designer.
Public Shared Function GetDataSet(ByVal adapter As System.Data.OleDb.OleDbDataAdapter, ByVal defaultDataSet As Namespace.DataSetCustomers) As Namespace.DataSetCustomers
If dataSet11 Is Nothing Then
dataSet11 = New Namespace.DataSetCustomers()
CType(dataSet11, System.ComponentModel.ISupportInitialize).BeginInit()
dataSet11.DataSetName = defaultDataSet.DataSetName
dataSet11.EnforceConstraints = defaultDataSet.EnforceConstraints
dataSet11.Locale = defaultDataSet.Locale
CType(dataSet11, System.ComponentModel.ISupportInitialize).EndInit()
adapter.Fill(dataSet11)
End If
Return dataSet11
End Function
#End Region
'Filling a DataAdapter using static datasource. Instead of filling a DataAdapter with the dataset created in the designer, you can use the static data source.
'this.oleDbDataAdapter1.Fill(this.dataSetCustomers1);
'Using a static datasource, changes made to the dataset will be preserved across postback.
Private Me.dataSetCustomers1 = GetDataSet(Me.oleDbDataAdapter1, Me.dataSetCustomers1)