DataSet Class
Assembly: System.Data (in system.data.dll)
[SerializableAttribute] public class DataSet : MarshalByValueComponent, IListSource, IXmlSerializable, ISupportInitializeNotification, ISupportInitialize, ISerializable
/** @attribute SerializableAttribute() */ public class DataSet extends MarshalByValueComponent implements IListSource, IXmlSerializable, ISupportInitializeNotification, ISupportInitialize, ISerializable
The DataSet, which is an in-memory cache of data retrieved from a data source, is a major component of the ADO.NET architecture. The DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects. For further details about working with DataSet objects, see Using DataSets in ADO.NET.
Whereas DataTable objects contain the data, the DataRelationCollection allows you to navigate though the table hierarchy. The tables are contained in a DataTableCollection accessed through the Tables property. When accessing DataTable objects, note that they are conditionally case sensitive. For example, if one DataTable is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. For more information about working with DataTable objects, see Creating a DataTable.
A DataSet can read and write data and schema as XML documents. The data and schema can then be transported across HTTP and used by any application, on any platform that is XML-enabled. You can save the schema as an XML schema with the WriteXmlSchema method, and both schema and data can be saved using the WriteXml method. To read an XML document that includes both schema and data, use the ReadXml method.
In a typical multiple-tier implementation, the steps for creating and refreshing a DataSet, and in turn, updating the original data are to:
-
Build and fill each DataTable in a DataSet with data from a data source using a DataAdapter.
-
Change the data in individual DataTable objects by adding, updating, or deleting DataRow objects.
-
Invoke the GetChanges method to create a second DataSet that features only the changes to the data.
-
Call the Update method of the DataAdapter, passing the second DataSet as an argument.
-
Invoke the Merge method to merge the changes from the second DataSet into the first.
-
Invoke the AcceptChanges on the DataSet. Alternatively, invoke RejectChanges to cancel the changes.
Note |
|---|
| The DataSet and DataTable objects inherit from MarshalByValueComponent, and support the ISerializable interface for remoting. These are the only ADO.NET objects that can be remoted. |
The following example consists of several methods that, combined, create and fill a DataSet from the Northwind database.
using System; using System.Data; using System.Data.SqlClient; namespace Microsoft.AdoNet.DataSetDemo { class NorthwindDataSet { static void Main() { string connectionString = GetConnectionString(); ConnectToData(connectionString); private static void ConnectToData(string connectionString) { //Create a SqlConnection to the Northwind database. using (SqlConnection connection = new SqlConnection(connectionString)) { //Create a SqlDataAdapter for the Suppliers table. SqlDataAdapter adapter = new SqlDataAdapter(); // A table mapping names the DataTable. adapter.TableMappings.Add("Table", "Suppliers"); // Open the connection. connection.Open(); Console.WriteLine("The SqlConnection is open."); // Create a SqlCommand to retrieve Suppliers data. SqlCommand command = new SqlCommand( "SELECT SupplierID, CompanyName FROM dbo.Suppliers;", connection); command.CommandType = CommandType.Text; // Set the SqlDataAdapter's SelectCommand. adapter.SelectCommand = command; // Fill the DataSet. DataSet dataSet = new DataSet("Suppliers"); adapter.Fill(dataSet); // Create a second Adapter and Command to get // the Products table, a child table of Suppliers. SqlDataAdapter productsAdapter = new SqlDataAdapter(); productsAdapter.TableMappings.Add("Table", "Products"); SqlCommand productsCommand = new SqlCommand( "SELECT ProductID, SupplierID FROM dbo.Products;", connection); productsAdapter.SelectCommand = productsCommand; // Fill the DataSet. productsAdapter.Fill(dataSet); // Close the connection. connection.Close(); Console.WriteLine("The SqlConnection is closed."); // Create a DataRelation to link the two tables // based on the SupplierID. DataColumn parentColumn = dataSet.Tables["Suppliers"].Columns["SupplierID"]; DataColumn childColumn = dataSet.Tables["Products"].Columns["SupplierID"]; DataRelation relation = new System.Data.DataRelation("SuppliersProducts", parentColumn, childColumn); dataSet.Relations.Add(relation); Console.WriteLine( "The {0 DataRelation has been created.", relation.RelationName); static private string GetConnectionString() { // To avoid storing the connection string in your code, // you can retrieve it from a configuration file. return "Data Source=(local);Initial Catalog=Northwind;" + "Integrated Security=SSPI";
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.
This example shows how to use DotNetZip to save the XML representation of a dataset into a .ZIP file, using an anonymous delegate. The DataSet XML is never saved to a filesystem file.
private System.Data.DataSet ds1;
private void SaveDatasetIntoZip(string entryName, Stream s)
{
ds1.WriteXml(s);
}
private void Run()
{
using (System.Data.SqlClient.SqlConnection c1=
new System.Data.SqlClient.SqlConnection(connstring1))
{
System.Data.SqlClient.SqlDataAdapter da =
new System.Data.SqlClient.SqlDataAdapter();
da.SelectCommand= new System.Data.SqlClient.SqlCommand(strSelect, c1);
ds1 = new DataSet();
da.Fill(ds1, "Invoices");
using(Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
zip.AddEntry(zipEntryName, SaveDatasetIntoZip );
zip.Save(zipFileName);
}
}
}
This example requires DotNetZip, a free downloadable ZIP library - http://dotnetzip.codeplex.com
DotNetZip also works from VB, of course.
In C# 3.0, the code can be simpler, via the use of anonymous methods.
The dataset is a very useful and powerful tool. One of the ways it can be used is as a strongly typed dataset. The following MSDN article provides additional information on how to use datasets in this manner:
This tells you how to create datasets using XSDs. There's great information on traps for new players with strongly typed datasets such as property aliasing using codegen:typedName to change the name of properties, codegen:nullValue to load a default value rather than throwing those nasty DBNull exceptions - the above is assuming a codegen namespace for the following schema: xmlns:codegen="urn:schemas-microsoft-com:xml-msprop".
The best thing about Strongly typed datasets is that they inherit (along with the data tables and rows) from the base dataset classes - allowing you to cast an untyped dataset to a typed dataset very easily (making code much easier to read and maintain).
- 6/10/2006
- Daniel Thomas
- 6/10/2006
- Daniel Thomas
Note