DataSet In C#

ADO.NET DataSet

 
Most of the software applications (Windows, Web, or mobile) developed today involve some kind of data access and data manipulation including data retrieval, storage, change, translation, verification, or transportation. For an application to be scalable and interoperable, the app should be able to transport data in-memory. In-memory representation of data may include database tabel schema, its column types and relationships, and metadata. This is where ADO.NET DataSet plays a vital role.
 
ADO.NET DataSet is a data construct that can contain several relational rowsets, the relations that link those rowsets, and the metadata for each rowset. The DataSet also tracks which fields have changed, their new values and their original values, and can store custom information in its Extended Properties collection. The DataSet can be exported to XML or created from an XML document, thus enabling increased interoperability between applications.

When we look at the DataSet object model, we see that it is made up of three collections; Tables, Relations, and ExtendedProperties. These collections make up the relational data structure of the DataSet. The DataSet.Tables property is a DataTableCollection object, which contains zero or more DataTable objects. Each DataTable represents a table of data from the data source. Each DataTable is made p of a Columns collection and a Rows collection, which are zero or more DataColumns or DataRows, in that order.

The Relations property as a DataRelationCollection object, which contains zero or more DataRelation objects. The DataRelation objects define a parent-child relationship between two tables based on foreign key values. On the other hand, The ExtendedProperties property is a PropertyCollection object, which contains zero or more user-defined properties. The ExtendedProperties collection can be used contains zero or more user-defined properties. This property collection can be used to store custom data related to the DataSet, such as the time when the DataSet was constructed.

One of the key points to remember about the DataSet is that it doesn't care where it originated. Unlike the ADO 2.x Recordset, the DataSet doesn't track which database or XML document its data came from. In this way, the DataSet is a standalone data store that can be passed from tier to tier in an n-tiered architecture. This Article, we will continue by showing us how to use the DataSet in a .NET-based application to retrieve data, track modifications made by the user, and send the data back to the database.

Using C# .NET, we will show how to retrieve products from the Northwind database from a business services application and load the information in the presentation tier, all using .NET. We will walk through examples of how to use the DataSet to save several rows to the database at one time. The code samples will demonstrate how to send new rows, changed rows, and deleted rows in one trip to the business services tier and then on to the database by using a DataSet.

Working with .NET DataSets


Before we start, to understand the DataSet advanced techniques, we first have to recognize the DataTable. As a preview and reminder we will be discussing the DataTable class, and understanding how the DataTable works and its role in a data-driven application. Once we have worked with DataTables, we will begin using DataTables in DataSets, and building DataRelations between two DataTables, in the same way, we would have a relationship between two tables in a database. After everything, we will discuss how to cache DataSets for increased performance.

DataSet Constructors (SerializationInfo, StreamingContext)


This member supports the .NET Framework infrastructure and is not intended to be used directly from our code.
  1. public DataSet();  
  2. public DataSet(string dataSetName);  
  3. protected DataSet(SerializationInfo info, StreamingContext context);  

Object Serialization and the SerializationInfo Class


Serialization is the process of converting a graph of objects, into a linear sequence of bytes. That sequence of bytes can be sent elsewhere (for example, to a remote computer) and deserialized, this means making a clone in that remote memory of the original graph of objects. The process of serialization is effortless with .NET and its release too. When any class in ActiveX DLL or ActiveX exe is created, there are five properties of the class that can be set. The last property known as persistable is what serialization in C#. In C# with common object library, every language supporting .NET architecture known and can use Serialization Feature with the help of RunTime.Serialization Namespace.

When we complete serialization in .NET, the runtime metadata 'knows' all there is to know about each object's layout in memory, its field and property definitions, this makes serialization of objects automatically, without having to write code to serialize each field.
The serialized stream might be encoded using XML, or a compact binary representation. The format is decided by the Formatter object that is called. Pluggable formatters allow the developer to serialize objects in with the two supplied formats (binary and SOAP) or can be created by developers. Serialization can take place with any stream, not just a FileStream also Serialization makes use of several classes, as follows:
  • Formatter
    Responsible for writing object data in some specified format to the output stream. This class is also responsible for driving the deserialization operation.

  • ObjectIDGenerator
    ObjectIDGenerator generates IDs for objects. It keeps track of objects already 'seen' so that if you ask for the ID of an object, it knows whether to return its existing ID, or generate (and remember) a new ID.

  • ObjectManager
    Keeps track of objects as they are being deserialized. In this way, deserialization can query the ObjectManager to know whether a reference to an object, in the serialized stream, refers to an object that has already been deserialized (a backward reference), or to an object that has not yet been deserialized (a forward reference).

Each of these components is 'Pluggable' - the programmer can provide alternatives.

If a class author wishes to take special action when objects of that class are serialized and deserialized, he can choose to implement the ISerializable interface. This allows full control. For example, the author may define his own, custom SerializationInfo, to describe parts of the object or synthesized fields that capture the object state for serialization. If a class implements ISerializable, that interface will always be called in preference to default serialization. An important note on deserialization is that we return the fields in the same order in which they are returned from Reflection. Reflection makes no guarantee that it will follow metadata ordering.

This class holds all the data needed to serialize or deserialize an object. Attention please; this class cannot be inherited.

  1. publicsealedclass SerializationInfo  
Any public static members of this type are safe for multithreaded operations. Any instance members are not guaranteed to be thread-safe. This class is used by objects with custom serialization behavior. The GetObjectData method on either ISerializable or ISerializationSurrogate populates the SerializationInfo with the name, type, and value of each piece of information it wants to serialize. During deserialization, the appropriate function can extract this information. Objects are added to the SerializationInfo at serialization time using the AddValue methods and extracted from the SerializationInfo at deserialization using the GetValue methods.

The following code example demonstrates the SerializationInfo for custom serialization and deserialization of various values.
  1. using System;  
  2. using System.IO;  
  3. using System.Runtime.Serialization;  
  4. using System.Runtime.Serialization.Formatters.Binary;  
  5. namespace Testing {  
  6.     publicclass Test {  
  7.         publicstaticvoid Main(String[] args) {  
  8.             // Creates a new ExampleClass1 object.  
  9.             ExampleClass1 f = new ExampleClass1();  
  10.             // Opens a file and serializes the object into it in binary format.  
  11.             Stream stream = File.Open("ExampleClass1ExampleClass2.bin", FileMode.Create);  
  12.             BinaryFormatter bformatter = new BinaryFormatter();  
  13.             formatter.Serialize(stream, f);  
  14.             stream.Close();  
  15.             //Clean f.  
  16.             f = null;  
  17.             // Opens file "ExampleClass1ExampleClass2.bin" and deserializes the ExampleClass1   
  18.             // object from it.  
  19.             stream = File.Open("ExampleClass1ExampleClass2.bin", FileMode.Open);  
  20.             bformatter = new BinaryFormatter();  
  21.             f = (ExampleClass1) bformatter.Deserialize(stream);  
  22.             stream.Close();  
  23.         }  
  24.     }  
  25.     [Serializable()]  
  26.     publicclass ExampleClass1: ISerializable {  
  27.         public ExampleClass2 someObject;  
  28.         publicint size;  
  29.         public String shape;  
  30.         //Default constructor  
  31.         public ExampleClass1() {  
  32.             someObject = new ExampleClass2();  
  33.         }  
  34.         //Deserialization constructor.  
  35.         public ExampleClass1(SerializationInfo info, StreamingContext context) {  
  36.             size = (int) info.GetValue("size"typeof(int));  
  37.             shape = (String) info.GetValue("shape"typeof(string));  
  38.             //Allows ExampleClass2 to deserialize itself  
  39.             someObject = new ExampleClass2(info, context);  
  40.         }  
  41.         //Serialization function.  
  42.         publicvoid GetObjectData(SerializationInfo info, StreamingContext context) {  
  43.             info.AddValue("size", size);  
  44.             info.AddValue("shape", shape);  
  45.             //Allows ExampleClass2 to serialize itself  
  46.             someObject.GetObjectData(info, context);  
  47.         }  
  48.     }  
  49.     publicclass ExampleClass2 {  
  50.         publicdoublevalue = 3.14159265;  
  51.         public ExampleClass2() {}  
  52.         public ExampleClass2(SerializationInfo info, StreamingContext context) {  
  53.             value = (double) info.GetValue("ExampleClass2_value"typeof(double));  
  54.         }  
  55.         publicvoid GetObjectData(SerializationInfo info, StreamingContext context) {  
  56.                 info.AddValue("ExampleClass2_value", value); {}   
There are two types of DataSets - typed and untyped. 
 
A DataSet used in the above examples are untyped DataSets. Lean more on Typed DataSets in ADO.NET and C#.
 
A DataSet can represent one more database tables. A table representation in ADO.NET is a DataTable object. 
 


Similar Articles