7.4 Typed DataSets
One of the functions performed by XSD.exe, the XML schema generation tool, is to generate a typed DataSet from an XSD schema. This functionality is also available in Visual Studio as a menu item and context menu entry on an existing "DataAdapter object." What exactly is a typed DataSet?
A typed DataSet is a subclass of System.Data.DataSet in which the tables that exist in the DataSet are derived by reading the XSD schema information. The difference between a typed DataSet and an "ordinary" DataSet is that the DataRows, DataTables, and other items are available as strong types; that is, rather than refer to DataSet.Tables[0] or DataSet.Tables["customers"], you code against a strongly typed DataTable named, for example, MyDataSet.Customers. Typed DataSets have the advantage that the strongly typed variable names can be checked at compile time rather than causing errors at runtime. A short example will illustrate this concept.
Suppose you have a DataSet that should contain a table named customers. It should have columns named custid and custname. You can refer to the table and the columns by ordinal or by name. As shown in Listing 721, the data is loosely typed when referred to by ordinal or name, meaning that the compiler cannot guarantee that you've spelled the column name correctly or used the correct ordinal. The problem is that the error informing you of this occurs at runtime rather than at compile time. If the DataSet items were strongly typed, misspelling the column name or using the wrong ordinal would be prevented because the code simply would not compile.
Listing 721 Referring to DataTables and Columns
DataSet ds = new DataSet(); // some action to load the DataSet... // this will fail if second table does not exist String name = ds.Tables[1].TableName; // this will fail if the table is named customers DataTable t = ds.Tables["customesr"]; // This will fail if the DataRow r has fewer than 5 columns // or if column 5 is a String data type DataRow r; int value = (int)r[4]; // This will fail if there is a column named "custname" String value = r["custnam"].ToString();
This does not solve every problem; mismatches can still occur if the database schema changes between the time the typed DataSet was generated and runtime. But because the structure of the DataSet is built into the names, the compiler can catch the misspellings. The examples in Listing 722 illustrate this.
Listing 722 Strong typing in DataSet
// this fails at compile time if the name of // the table should be "customers" DataTable t = MyDataSet.Customesr; // so does this, should be custname String value = MyDataSet.Customers[0].custnam;
The easiest way to generate a typed DataSet corresponding to an existing database resultset is through Visual Studio or XSD.exe, using an existing table, stored procedure, SQL statement, or in the case of XSD.exe, an XML schema. In Visual Studio, you can create a typed DataSet from any DataAdapter object that has been dropped on a form, as shown in Figure 72. The Visual Studio designer instan
The manual equivalent of this is to Fill a DataSet, save the schema with DataSet.WriteXmlSchema, and then use the schema as input into XSD.exe. For example, let's generate a typed DataSet for the simple one-table case shown in Listing 723 and see what we get.
Figure 7-2 Generating a typed DataSet in Visual Studio.
Listing 723 Producing input for a typed DataSet
SqlDataAdapter da = new SqlDataAdapter( "select * from jobs", "server=localhost;uid=sa;database=pubs"); // name the DataSet MyDS DataSet ds = new DataSet("MyDS"); // name the table MyTable da.Fill(ds, "MyTable"); ds.WriteXmlSchema("myschema.xsd");
Listing 724 shows the complete source code for the sample typed DataSet.
Listing 724 A typed DataSet subclass generated by XSD.exe
// // This source code was auto-generated by xsd // using System; using System.Data; using System.Xml; using System.Runtime.Serialization; [Serializable()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Diagnostics.DebuggerStepThrough()] [System.ComponentModel.ToolboxItem(true)] public class JobsDS : DataSet { private jobsDataTable tablejobs; public JobsDS() { this.InitClass(); System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new System.ComponentModel.CollectionChangeEventHandler( this.SchemaChanged); this.Tables.CollectionChanged += schemaChangedHandler; this.Relations.CollectionChanged += schemaChangedHandler; } protected JobsDS(SerializationInfo info, StreamingContext context) { string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string)))); if ((strSchema != null)) { DataSet ds = new DataSet(); ds.ReadXmlSchema(new XmlTextReader(new System.IO.StringReader(strSchema))); if ((ds.Tables["jobs"] != null)) { this.Tables.Add(new jobsDataTable(ds.Tables["jobs"])); } this.DataSetName = ds.DataSetName; this.Prefix = ds.Prefix; this.Namespace = ds.Namespace; this.Locale = ds.Locale; this.CaseSensitive = ds.CaseSensitive; this.EnforceConstraints = ds.EnforceConstraints; this.Merge(ds, false, System.Data.MissingSchemaAction.Add); this.InitVars(); } else { this.InitClass(); } this.GetSerializationData(info, context); System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new System.ComponentModel.CollectionChangeEventHandler( this.SchemaChanged); this.Tables.CollectionChanged += schemaChangedHandler; this.Relations.CollectionChanged += schemaChangedHandler; } [System.ComponentModel.Browsable(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute( System.ComponentModel.DesignerSerializationVisibility.Content)] public jobsDataTable jobs { get { return this.tablejobs; } } public override DataSet Clone() { JobsDS cln = ((JobsDS)(base.Clone())); cln.InitVars(); return cln; } protected override bool ShouldSerializeTables() { return false; } protected override bool ShouldSerializeRelations() { return false; } protected override void ReadXmlSerializable(XmlReader reader) { this.Reset(); DataSet ds = new DataSet(); ds.ReadXml(reader); if ((ds.Tables["jobs"] != null)) { this.Tables.Add(new jobsDataTable(ds.Tables["jobs"])); } this.DataSetName = ds.DataSetName; this.Prefix = ds.Prefix; this.Namespace = ds.Namespace; this.Locale = ds.Locale; this.CaseSensitive = ds.CaseSensitive; this.EnforceConstraints = ds.EnforceConstraints; this.Merge(ds, false, System.Data.MissingSchemaAction.Add); this.InitVars(); } protected override System.Xml.Schema.XmlSchema GetSchemaSerializable() { System.IO.MemoryStream stream = new System.IO.MemoryStream(); this.WriteXmlSchema(new XmlTextWriter(stream, null)); stream.Position = 0; return System.Xml.Schema.XmlSchema.Read(new XmlTextReader(stream), null); } internal void InitVars() { this.tablejobs = ((jobsDataTable)(this.Tables["jobs"])); if ((this.tablejobs != null)) { this.tablejobs.InitVars(); } } private void InitClass() { this.DataSetName = "JobsDS"; this.Prefix = ""; this.Namespace = ""; this.Locale = new System.Globalization.CultureInfo ("en-US"); this.CaseSensitive = false; this.EnforceConstraints = true; this.tablejobs = new jobsDataTable(); this.Tables.Add(this.tablejobs); } private bool ShouldSerializejobs() { return false; } private void SchemaChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e) { if ((e.Action == System.ComponentModel.CollectionChangeAction.Remove)) { this.InitVars(); } } public delegate void jobsRowChangeEventHandler(object sender, jobsRowChangeEvent e); [System.Diagnostics.DebuggerStepThrough()] public class jobsDataTable : DataTable, System.Collections.IEnumerable { private DataColumn columnjob_id; private DataColumn columnjob_desc; private DataColumn columnmin_lvl; private DataColumn columnmax_lvl; internal jobsDataTable() : base("jobs") { this.InitClass(); } internal jobsDataTable(DataTable table) : base(table.TableName) { if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { this.CaseSensitive = table.CaseSensitive; } if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { this.Locale = table.Locale; } if ((table.Namespace != table.DataSet.Namespace)) { this.Namespace = table.Namespace; } this.Prefix = table.Prefix; this.MinimumCapacity = table.MinimumCapacity; this.DisplayExpression = table.DisplayExpression; } [System.ComponentModel.Browsable(false)] public int Count { get { return this.Rows.Count; } } internal DataColumn job_idColumn _ get { return this.columnjob_id; } } internal DataColumn job_descColumn { return this.columnjob_desc; } } internal DataColumn min_lvlColumn { get { return this.columnmin_lvl; } } internal DataColumn max_lvlColumn { get { return this.columnmax_lvl; } } public jobsRow this[int index] { get { return ((jobsRow)(this.Rows[index])); } } public event jobsRowChangeEventHandler jobsRowChanged; public event jobsRowChangeEventHandler jobsRowChanging; public event jobsRowChangeEventHandler jobsRowDeleted; public event jobsRowChangeEventHandler jobsRowDeleting; public void AddjobsRow(jobsRow row) this.Rows.Add(row); } public jobsRow AddjobsRow(string job_desc, System.Byte min_lvl, System.Byte max_lvl) { jobsRow rowjobsRow = ((jobsRow)(this.NewRow())); rowjobsRow.ItemArray = new object[] { null, job_desc, min_lvl, max_lvl}; this.Rows.Add(rowjobsRow); return rowjobsRow; } public jobsRow FindByjob_id(short job_id) { return ((jobsRow)(this.Rows.Find(new object[] { job_id}))); } public System.Collections.IEnumerator GetEnumerator() { return this.Rows.GetEnumerator(); } public override DataTable Clone() jobsDataTable cln = ((jobsDataTable)(base.Clone())); cln.InitVars(); return cln; } protected override DataTable CreateInstance() { return new jobsDataTable(); } internal void InitVars() { this.columnjob_id = this.Columns["job_id"]; this.columnjob_desc = this.Columns["job_desc"]; this.columnmin_lvl = this.Columns["min_lvl"]; this.columnmax_lvl = this.Columns["max_lvl"]; } private void InitClass() { this.columnjob_id = new DataColumn("job_id", typeof(short), null, System.Data.MappingType.Element); this.Columns.Add(this.columnjob_id); this.columnjob_desc = new DataColumn("job_desc", typeof(string), null, System.Data.MappingType.Element); this.Columns.Add(this.columnjob_desc); this.columnmin_lvl = new DataColumn("min_lvl", typeof(System.Byte), null, System.Data.MappingType.Element); this.Columns.Add(this.columnmin_lvl); this.columnmax_lvl = new DataColumn("max_lvl", typeof(System.Byte), null, System.Data.MappingType.Element); this.Columns.Add(this.columnmax_lvl); this.Constraints.Add(new UniqueConstraint ("Constraint1", new DataColumn[] {this.columnjob_id}, true)); this.columnjob_id.AutoIncrement = true; this.columnjob_id.AllowDBNull = false; this.columnjob_id.ReadOnly = true; this.columnjob_id.Unique = true; this.columnjob_desc.AllowDBNull = false; this.columnjob_desc.MaxLength = 50; this.columnmin_lvl.AllowDBNull = false; this.columnmax_lvl.AllowDBNull = false; } public jobsRow NewjobsRow() { return ((jobsRow)(this.NewRow())); } protected override DataRow NewRowFromBuilder( DataRowBuilder builder) { return new jobsRow(builder); } protected override System.Type GetRowType() { return typeof(jobsRow); } protected override void OnRowChanged( DataRowChangeEventArgs e) { base.OnRowChanged(e); if ((this.jobsRowChanged != null)) { this.jobsRowChanged(this, new jobsRowChangeEvent( ((jobsRow)(e.Row)), e.Action)); } } protected override void OnRowChanging(DataRowChangeEventArgs e) { base.OnRowChanging(e); if ((this.jobsRowChanging != null)) { this.jobsRowChanging(this, new jobsRowChangeEvent( ((jobsRow)(e.Row)), e.Action)); } } protected override void OnRowDeleted(DataRowChangeEventArgs e) { base.OnRowDeleted(e); if ((this.jobsRowDeleted != null)) { this.jobsRowDeleted(this, new jobsRowChangeEvent( ((jobsRow)(e.Row)), e.Action)); } } protected override void OnRowDeleting(DataRowChangeEventArgs e) base.OnRowDeleting(e); if ((this.jobsRowDeleting != null)) { this.jobsRowDeleting(this, new jobsRowChangeEvent( ((jobsRow)(e.Row)), e.Action)); } } public void RemovejobsRow(jobsRow row) { this.Rows.Remove(row); } } [System.Diagnostics.DebuggerStepThrough()] public class jobsRow : DataRow _par private jobsDataTable tablejobs; internal jobsRow(DataRowBuilder rb) : base(rb) { this.tablejobs = ((jobsDataTable)(this.Table)); } public short job_id { get { return ((short)(this[this.tablejobs.job_idColumn])); } set { this[this.tablejobs.job_idColumn] = value; } } public string job_desc { get { return ((string)(this[this.tablejobs.job_descColumn])); } set { this[this.tablejobs.job_descColumn] = value; } } public System.Byte min_lvl get { return ((System.Byte) (this[this.tablejobs.min_lvlColumn])); } set { this[this.tablejobs.min_lvlColumn] = value; } } public System.Byte max_lvl get { return ((System.Byte) (this[this.tablejobs.max_lvlColumn])); } set { this[this.tablejobs.max_lvlColumn] = value; } } } [System.Diagnostics.DebuggerStepThrough()] public class jobsRowChangeEvent : EventArgs { private jobsRow eventRow; private DataRowAction eventAction; public jobsRowChangeEvent(jobsRow row, DataRowAction action) { this.eventRow = row; this.eventAction = action; } public jobsRow Row { get { return this.eventRow; } } public DataRowAction Action { get { return this.eventAction; } } } }
The typed DataSet accomplishes strong typing by generating a class MyDS, which derives from DataSet (1). The name of the subclass of the DataSet class is equal to DataSet.DataSetName in the original DataSet that produced the XML schema. Four public nested classes are exposed:
MyDS.MyTabDataTable:DataTable, IEnumerable
MyDS.MyTabRow:DataRow
MyDS.MyTabRowChangeEvent:EventArgs
MyDS.MyTabRowChangeEventHandler
where
MyDS is the DataSet.DataSetName
MyTab is the DataTable.TableName
MyTabRow is DataTable.TableName + Row
MyDS.MyTabDataTable has a series of private DataColumn members; one data member per column is the table or resultset. There are getters for these, but they are marked internal because you are not allowed to add or delete DataColumns at runtime. There are also four typed delegates for Changing, Changed, Deleting, and Deleted rows.
The typed DataTable has the following methods:
An Indexer for Rows and a GetEnumerator method.
Two add methods, both called AddMyTabRow but each used a little differently. AddMyTabRow(row), which takes a Row, is used with NewMyTabRow, an empty typed row. AddMyTabRow(n1,n2,n3)takes N parms, where N is the number of columns in the table and MyTab is a placeholder. For example, if the table name were equal to Jobs, the method name would be AddJobsRow.
RemoveMyTabRow, a delete method.
The DataColumns are created and added to the DataTable in the DataTable's InitClass method. If metadata is available, it is also filled in at that time. If there is a primary key or unique column, there is a method called FindBykeycolname that uses the primary key as input.
The MyDSRow class exposes columns as public properties. If the column is nullable, there are two predefined helper functionsIsColumnnameNull and SetColumnnameNullwhere Columnname is a placeholder for the name of the column.
To delete a DataRow provided by strongly typed DataSets, you would use the convenience method DataRowCollection.Remove rather than Data-Row.Delete. But the two methods have different semantics. The difference between the two is that calling DataRowCollection.Remove is the same as calling DataRow.Delete followed by AcceptChanges. If you use Remove and then use the DataSet to update a database through a DataAdapter, the rows that you deleted in the DataSet using Remove will not be deleted in the database. If this is the desired behavior, you should use DataRow.Delete instead of the convenience RemoveMyTabRow method.
A strongly typed DataSet can also contain more than one table. If you have tables with parent-child relationshipsspecified by the existence of a DataRelation in the DataSet's Relations collectionsome additional information and methods are generated. When the DataSet contains a Relation, the following things happen:
The PrimaryKey property is added to DataColumn properties for the parent table, a ForeignKeyConstraint is added for the child table, and DataRelation is added. If the DataSet's Nested property was set in the original schema, it is preserved in the typed DataSet.
ChildTabRow has a property of type ParentTabRow. A property's get method calls GetParentRow, and the setter calls SetParent.
ParentRow has a method, GetChildTabRow, that returns an array of typed child rows by calling GetChildRows.
where
ParentTab is the DataTable.TableName of the parent table.
ChildTab is the DataTable.TableName of the child table.
Finally, the strongly typed DataSet has certain methods and a property that are related to XML persistence. These override the DataSet's methods.
A protected constructor takes a SerializationInfo info and a StreamingContext context. This constructor calls InitClass before calling GetSerializationData. This is a requirement when you implement ISerializable.
ReadXmlSerializable simply calls the base class's ReadXml method.
GetSchemaSerializable calls WriteXmlSchema to write the schema to an XmlTextWriter. Then it reads it back into a System.Xml.Schema.XmlSchema. This is similar to the code in the base class (DataSet).
The properties ShouldSerializeTables and ShouldSerialize-Relations, and an additional property called ShouldSerialize[MyTable], return false.
The example in Listing 725 uses every method of a one-DataTable typed DataSet and a hierarchical typed DataSet with a parent-child relationship. Typed DataSets can also be used as ordinary DataSets, with a corresponding loss of compile-type syntax checking.
Listing 725 Using a Typed DataSet
using System; using System.Data; using System.Data.SqlClient; namespace UseDataSet { class Class1 { static void Main(string[] args) { Class1 c = new Class1(); c.instanceMain(); } void instanceMain() { UseJobsWithDBMS(); UseJobsDS(); UseAuTitleDS(); } void UseJobsWithDBMS() { try { JobsDS j = new JobsDS(); SqlDataAdapter da = new SqlDataAdapter( "select * from jobs", "server=localhost;uid=sa;database=pubs"); SqlCommandBuilder bld = new SqlCommandBuilder(da); da.Fill(j.jobs); Console.WriteLine(j.jobs.Rows.Count); JobsDS.jobsRow found_row = j.jobs.FindByjob_id(156); Console.WriteLine(j.jobs.Rows.Count); //j.jobs.RemovejobsRow(found_row); found_row.Delete(); Console.WriteLine(j.jobs.Rows.Count); da.Update(j.jobs); } catch (Exception e) { Console.WriteLine(e.Message); } } protected void T_Changing(object sender, JobsDS.jobsRowChangeEvent e) { if (e.Row.RowState == DataRowState.Deleted) Console.WriteLine("Row Changing: Action {0}, State {1}", e.Action, e.Row.RowState); else Console.WriteLine("Row Changing: {0} id = {1}, State {2}", e.Action, e.Row[0], e.Row.RowState); } protected void T_Changed(object sender, JobsDS.jobsRowChangeEvent e) { if (e.Row.RowState == DataRowState.Detached) Console.WriteLine("Row Changed: Action {0}, State {1}", e.Action, e.Row.RowState); else Console.WriteLine("Row Changed: {0} id = {1}, State {2}", e.Action, e.Row[0], e.Row.RowState); } protected void T_Deleting(object sender, JobsDS.jobsRowChangeEvent e) { Console.WriteLine("Row Deleting: {0} id = {1}, State {2}", e.Action, e.Row[0], e.Row.RowState); } protected void T_Deleted(object sender, JobsDS.jobsRowChangeEvent e) { Console.WriteLine("Row Deleted: Action {0}, State {1}", e.Action, e.Row.RowState); } void UseJobsDS() { // 1. One public class JobsDS // 2. Four public nested classes: // JobsDS.jobsDataTable; // JobsDS.jobsRow; // JobsDS.jobsRowChangeEvent; // JobsDS.jobsRowChangeEventHandler; // Generates one named high-level type // the DataSet JobsDS j = new JobsDS(); Console.WriteLine(j.DataSetName); // event handlers j.jobs.jobsRowChanging += new JobsDS.jobsRowChangeEventHandler(T_Changing); j.jobs.jobsRowChanged += new JobsDS.jobsRowChangeEventHandler(T_Changed); j.jobs.jobsRowDeleting += new JobsDS.jobsRowChangeEventHandler(T_Deleting); j.jobs.jobsRowDeleted += new JobsDS.jobsRowChangeEventHandler(T_Deleted); // The DataSet has a single new property named "jobs" // It's also a public nested class JobsDS.jobsDataTable t = j.jobs; Console.WriteLine(j.jobs.TableName); // add a row //j.jobs.AddjobsRow(99, "new job", 20, 20); // when you have metadata, it's smarter about this // you can't add the identity column j.jobs.AddjobsRow("new job", 20, 20); // or add a row // through the jobsRow public nested class JobsDS.jobsRow r = j.jobs.NewjobsRow(); // convenience columns //r.job_id = 100; r.job_desc = "job 100"; r.max_lvl = 90; r.min_lvl = 89; j.jobs.AddjobsRow(r); // convenience IsNull functions // only if it can be null //if (r.Isjob_descNull() == true) // Console.WriteLine("desc is null"); // and SetNull functions //r.Setjob_idNull(); // jobs exposes a public property Count == table.Rows.Count Console.WriteLine("row count is " + j.jobs.Count); // convenience find function JobsDS.jobsRow found_row = j.jobs.FindByjob_id(1) Console.WriteLine(j.jobs.Rows.Count); // strongly typed //j.jobs.RemovejobsRow(r); j.jobs.RemovejobsRow(found_row); Console.WriteLine(j.jobs.Rows.Count); // 4 DataColumns as members. //j.jobs.job_idColumn; //j.jobs.job_descColumn; //j.jobs.max_lvlColumn; //j.jobs.min_lvlColumn; if (j.jobs.job_idColumn.ReadOnly == true) Console.WriteLine("its read only"); Console.WriteLine(j.jobs[0].job_desc); // change the first column // this would fail, column is readonly //j.jobs[0].job_id = 98; j.jobs[0].job_desc = "new description"; j.AcceptChanges(); j.WriteXmlSchema("theschema.xsd"); j.WriteXml("thedocument.xml"); JobsDS j2 = new JobsDS(); // fails, the typed DataSet already contains the typed table. //j2.ReadXmlSchema("jobsds.xsd"); j2.ReadXml("jobsds.xml"); } void UseAuTitleDS() { try { SqlDataAdapter da = new SqlDataAdapter( "select * from authors;select * from titleauthor", "server=localhost;uid=sa;database=pubs"); AuTitleDS om = new AuTitleDS(); // we still must map these because the // mapping is on the DataAdapter da.TableMappings.Add("Table", "authors"); da.TableMappings.Add("Table1", "titleauthors"); da.Fill(om); Console.WriteLine("{0} tables", om.Tables.Count); AuTitleDS.authorsRow r = om.authors[0]; // get array of children AuTitleDS.titleauthorsRow[] cr = r.GettitleauthorsRows(); foreach (AuTitleDS.titleauthorsRow tr in cr) { Console.WriteLine("author {0}, title {1}", tr.au_id, tr.title_id); AuTitleDS.authorsRow ar = tr.authorsRow; Console.WriteLine("author {0} is the parent", ar.au_id); } } catch (Exception e) { Console.WriteLine(e.Message); } } } }
Although strongly typed DataSets are produced using the names in the schema, you can refine the naming process by using certain schema annotations. These attributes are specified on the element declaration that equates to the table. The annotations are as follows:
typedName: Name of an object referring to a row
typedPlural: Name of an object referring to a table
typedParent: Name of a parent object in a parent-child relationship
typedChild: Name of a child object in a parent-child relationship
There is also an annotation, nullValue, that refers to special handling in a strongly typed DataSet when the value in the underlying table is DBNull.