A DataSet is a central object in ADO.NET for working with data. It is an in-memory representation of data that can be used to hold multiple tables of data, relationships between them, and constraints. Unlike DataReader, which provides a forward-only, read-only way of accessing data, a DataSet provides a more flexible, disconnected model where data can be manipulated and used in various ways.
A DataSet allows you to work with data from different sources (e.g., SQL Server, Oracle, etc.), without requiring a constant connection to the database. The data can be loaded, edited, and saved back to the database when necessary.
A DataSet is a collection of DataTable objects, where each DataTable contains rows and columns of data, and you can also define relationships between tables (such as foreign key relationships). Additionally, the DataSet can include constraints (such as primary key constraints) and other metadata for the data it holds.
A DataSet is disconnected, meaning it does not maintain a live connection to the database once data has been loaded into it. You can edit the data offline and later update the database with the changes.
The key components of a DataSet are:
DataTable, specifying the type of data each column holds.DataTable.DataTable objects (similar to foreign keys).You can create a DataSet and populate it in several ways, such as by using DataAdapter to fill it with data from a database. The DataAdapter acts as a bridge between the database and the DataSet. It retrieves data from the database and populates the DataSet, and can also be used to update the database.
The following example demonstrates how to create a DataSet, populate it using a DataAdapter, and display the data in a DataTable.
using System;
using System.Data;
using System.Data.SqlClient;
public class DataSetExample
{
public void LoadDataSet()
{
string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabase;Integrated Security=True";
string query = "SELECT EmployeeID, FirstName, LastName, Age FROM Employees";
// Create a DataSet object
DataSet dataSet = new DataSet();
// Create a SqlConnection and SqlDataAdapter
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
// Fill the DataSet with data from the database
adapter.Fill(dataSet, "Employees");
// Now, the DataSet contains the data in the "Employees" table
}
// Access the DataTable from the DataSet
DataTable employeeTable = dataSet.Tables["Employees"];
// Display the data from the DataTable
foreach (DataRow row in employeeTable.Rows)
{
Console.WriteLine($"ID: {row["EmployeeID"]}, Name: {row["FirstName"]} {row["LastName"]}, Age: {row["Age"]}");
}
}
}
DataSet object is created, and a DataAdapter is used to fetch data from the database.SqlDataAdapter.Fill() method fills the DataSet with data from the database using the SQL query.DataSet under the name "Employees". You can access this DataTable and read the data from it.A DataSet can contain multiple DataTable objects, allowing you to work with more than one table of data at once. You can access these tables by their name or index.
DataSet dataSet = new DataSet();
// Add DataTables to the DataSet
DataTable employeesTable = new DataTable("Employees");
DataTable departmentsTable = new DataTable("Departments");
dataSet.Tables.Add(employeesTable);
dataSet.Tables.Add(departmentsTable);
// Fill the DataTables with data (using SqlDataAdapter or manually)
You can use the Tables collection of the DataSet to manage and access multiple tables:
DataTable employees = dataSet.Tables["Employees"];
DataTable departments = dataSet.Tables["Departments"];
A DataSet can also contain relationships between different DataTable objects. These relationships allow you to represent the foreign key relationships between tables (such as between an Employees table and a Departments table).
DataSet dataSet = new DataSet();
// Create the DataTables
DataTable employees = new DataTable("Employees");
DataTable departments = new DataTable("Departments");
// Add columns to the Employees table
employees.Columns.Add("EmployeeID", typeof(int));
employees.Columns.Add("FirstName", typeof(string));
employees.Columns.Add("DepartmentID", typeof(int));
// Add columns to the Departments table
departments.Columns.Add("DepartmentID", typeof(int));
departments.Columns.Add("DepartmentName", typeof(string));
// Add the tables to the DataSet
dataSet.Tables.Add(employees);
dataSet.Tables.Add(departments);
// Define a relationship between the tables
DataRelation relation = new DataRelation(
"EmployeeDepartmentRelation",
departments.Columns["DepartmentID"],
employees.Columns["DepartmentID"]);
dataSet.Relations.Add(relation);
In this example, the DataRelation object is used to define the relationship between the Employees table and the Departments table, linking the DepartmentID column in both tables.
Once the data is in a DataSet, you can perform various operations on it, such as:
Adding rows: You can use the NewRow() method of the DataTable to create a new row and then add it to the table using Rows.Add().
Modifying data: You can directly modify the values in a DataRow object.
Deleting rows: You can mark rows for deletion using the Delete() method of the DataRow object.
// Adding a new row
DataRow newRow = employees.NewRow();
newRow["EmployeeID"] = 101;
newRow["FirstName"] = "John";
newRow["DepartmentID"] = 1;
employees.Rows.Add(newRow);
// Modifying an existing row
DataRow existingRow = employees.Rows[0];
existingRow["FirstName"] = "Jane";
// Deleting a row
DataRow rowToDelete = employees.Rows[1];
rowToDelete.Delete();
After modifying the DataSet, you can use a DataAdapter to update the database. The Update() method of the DataAdapter is used to push changes back to the database. The DataAdapter will automatically generate the appropriate INSERT, UPDATE, or DELETE commands based on the changes made to the DataSet.
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Employees", connectionString))
{
SqlCommandBuilder builder = new SqlCommandBuilder(adapter); // Generates commands for Insert, Update, Delete
// Apply changes made to the DataSet
adapter.Update(dataSet, "Employees");
}
This code uses SqlCommandBuilder to automatically generate the necessary SQL commands for updating, inserting, or deleting records in the database based on the changes made in the DataSet.
DataSet allows you to work with data without maintaining an open connection to the database. This is useful for scenarios where you want to perform offline data manipulation.DataSet, allowing you to work with complex data models.A DataSet is a powerful object in ADO.NET that allows you to work with data in a disconnected way, providing flexibility to manipulate and update data offline. It can hold multiple tables, define relationships between them, and supports operations like adding, modifying, and deleting rows. When combined with a DataAdapter, you can easily interact with the database, making it a key component for applications requiring robust data management.
DataSet when you need to work with multiple tables, need to manipulate data offline, or require relational data.Open this section to load past papers