Fill a DataSet with a SQL Server query

A DataSet stores disconnected tables in memory. SqlDataAdapter.Fill executes its select command and loads those tables, which is useful for code that already consumes ADO.NET table structures.

Filling a table does not track a live database connection or automatically persist later edits.

Load a named table

Requires SQL Server and a .NET console project with Microsoft.Data.SqlClient. Set the DEMO_SQL_CONNECTION environment variable to an authorized connection string, then run:

C#
using System.Data;
using Microsoft.Data.SqlClient;

var cs = Environment.GetEnvironmentVariable("DEMO_SQL_CONNECTION")
	?? throw new InvalidOperationException("Set DEMO_SQL_CONNECTION.");
using var connection = new SqlConnection(cs);
using var command = new SqlCommand("SELECT @Id AS Id, N'Example' AS Name;", connection);
command.Parameters.Add("@Id", SqlDbType.Int).Value = 7;
using var adapter = new SqlDataAdapter(command);
var data = new DataSet();
adapter.Fill(data, "Items");
Console.WriteLine(data.Tables["Items"]!.Rows[0]["Name"]);

The output is Example. Because the connection began closed, Fill opens it for the operation and closes it afterward. An already-open connection remains the caller's responsibility.

Bound the result

Choose explicit columns and a selective query for a real table. Large disconnected results consume application memory. Fill is synchronous. Do not assume it becomes asynchronous because the surrounding method uses async.

Use a reader when you need streaming access, or asynchronous reader APIs for asynchronous database I/O. Updating a DataSet requires appropriate adapter commands and concurrency handling. Changing a cell alone does not send an UPDATE to the server.

Official references

Populating a DataSet from a DataAdapter - ADO.NET
Learn how to populate a DataSet from a DataAdapter in ADO.NET, which provides a consistent relational programming model independent of the data source.
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/populating-a-dataset-from-a-dataadapter
Populating a DataSet

Author: Herman Schoenfeld