In ADO.NET, disconnected data access means fetching data from a database, working with it in-memory (using
DataSet
, DataTable
, or DataView
), and not maintaining an active connection to the database.
DataView
operates on a DataTable
, which is disconnected from the database once data is retrieved. Below is a demonstration proving that
DataView
works without a continuous database connection.
Fetch Data from Database (Open Connection Only Once)
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
// Connection string (Modify based on your database)
string connectionString = "Server=your_server;Database=your_db;Integrated Security=True;";
// Disconnected data access: Fetch data once, then close connection
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
string query = "SELECT ID, Name, Age FROM Employees"; // Fetch data from DB
SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
adapter.Fill(dt); // Data loaded into DataTable (Disconnected)
conn.Close(); // Connection is now closed
}
// 💡 Proof: Data is stored in-memory. We no longer need the database connection.
Console.WriteLine("Database Connection is Closed!");
Console.WriteLine($"Total Rows Retrieved: {dt.Rows.Count}");
// Creating DataView from DataTable
DataView dv = new DataView(dt);
// Apply Sorting
dv.Sort = "Age ASC";
// Apply Filtering (Only employees older than 25)
dv.RowFilter = "Age > 25";
// Display Data (Working without DB connection)
Console.WriteLine("\nFiltered Employees (Age > 25):");
foreach (DataRowView row in dv)
{
Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}, Age: {row["Age"]}");
}
// Proving disconnection: Modify DataView without any DB connection
DataRowView newRow = dv.AddNew();
newRow["ID"] = 999;
newRow["Name"] = "John Doe";
newRow["Age"] = 35;
newRow.EndEdit();
Console.WriteLine("\nNew Row Added (Without DB Connection):");
foreach (DataRowView row in dv)
{
Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}, Age: {row["Age"]}");
}
}
}
Proof of Disconnected Access
- Database connection is opened only once to fetch data.
- Data is stored in
DataTable
(in-memory storage). DataView
operates independently without requiring a live database connection.- Sorting, filtering, and adding new rows happen without re-querying the database.
Leave Comment