Microsoft Learn

Documentation for developers

Connected vs. Disconnected Data Access in ADO.NET

ADO.NET provides two primary models for interacting with data sources: the connected and disconnected data access models. Understanding the differences and when to use each is crucial for efficient and effective data management in your .NET applications.

The Connected Data Access Model

In the connected data access model, your application maintains an active connection to the data source throughout the duration of data retrieval and manipulation. This model is characterized by the use of objects like Connection and Command, often in conjunction with a DataReader.

Characteristics:

Common Usage:

Example (Conceptual C#):


using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    string query = "SELECT CustomerID, CompanyName FROM Customers";
    SqlCommand command = new SqlCommand(query, connection);

    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.WriteLine($"ID: {reader["CustomerID"]}, Name: {reader["CompanyName"]}");
        }
    }
    // Connection is automatically closed here by the 'using' statement
}
            

The Disconnected Data Access Model

The disconnected data access model allows your application to retrieve data from a data source, close the connection, and then work with the data locally. This is achieved using DataSet and DataTable objects, often populated and updated via DataAdapter objects.

Characteristics:

Common Usage:

Example (Conceptual C#):


string connectionString = "your_connection_string";
string query = "SELECT OrderID, OrderDate FROM Orders";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
    DataSet dataSet = new DataSet();

    // Connection opens, data is filled, then connection closes
    adapter.Fill(dataSet, "Orders");

    // Work with dataSet.Tables["Orders"] disconnected from the database
    DataTable ordersTable = dataSet.Tables["Orders"];
    foreach (DataRow row in ordersTable.Rows)
    {
        Console.WriteLine($"Order ID: {row["OrderID"]}, Date: {row["OrderDate"]}");
    }

    // To update the database, you would typically use an SqlCommandBuilder
    // or explicitly define UPDATE, INSERT, DELETE commands on the DataAdapter.
}
            

Choosing the Right Model

The choice between connected and disconnected data access depends on your specific application requirements:

Hybrid Approach: It's also common to use a hybrid approach. For example, you might use the disconnected model to load data into a DataSet, and then use the connected model with DataReader for subsequent, quick lookups or updates based on the disconnected data.

Understanding these two models allows you to design more robust, scalable, and performant data-driven applications with ADO.NET.