6.2 Generating Typed DataSets
Now that you understand what Typed DataSets are all about, let's create our own. Typed DataSets can be generated in two ways: from within Visual Studio .NET or with the XSD.exe command-line tool. I will start with the Visual Studio .NET solution.
6.2.1 Using Visual Studio .NET to Create a Typed DataSet
This section will walk you through creating a Typed DataSet in Visual Studio. NET. To get started, please create a new Console C# project, as shown in Figure 6.3. Next, in the Solution Explorer add a new item, as shown in Figure 6.4.
Figure 6.3: Creating a new C# project
Figure 6.4: Adding a new item
From the Data folder in the Local Project Items, select a new DataSet and name it ADONET.xsd, as shown in Figure 6.5. If you add an XML Schema file instead (they both are .XSD files), the Typed DataSet will not generate. Make sure it is a DataSet. When you finish, the IDE will look something like what is shown in Figure 6.6.
Figure 6.5: Adding a DataSet
Figure 6.6: A blank canvas
You probably have noticed already that the Typed DataSet has an extension of .xsd. This is because the source of a Typed DataSet is an XML Schema Document. What the IDE asks you to do is to create a new .XSD file that represents the schema of the DataSet. This will include the schema information we discussed in Chapter 5. The XSD can include table and column names as well as keys, relationships, and constraints.
Now that you have a new Typed DataSet added to your project, you can use either the Server Explorer to add tables to the DataSet or the Toolbox to add elements to the DataSet. Using the Server Explorer to add tables is shown in Figure 6.7.
Figure 6.7: The Server Explorer
After you have the Server Explorer open to an existing database, you can simply drag and drop the tables you want onto the .XSD file, to produce something that looks like Figure 6.8.
Figure 6.8: Tables in the .XSD file
At this point, the new Typed DataSet will include two tables, but the tables remain unrelated. Unfortunately Visual Studio .NET does not try to discern all the schema information that may be contained in the database. In order to set the schema information, you will need to add it to the XSD.
We will start by adding a relationship between the Customer and Invoice tables. To do this, drag a new Relation from the Toolbox onto the Customer table, as shown in Figure 6.9. Once you do that, the Edit Relation dialog box appears, as shown in Figure 6.10.
Figure 6.9: Adding a relationship
Figure 6.10: The Edit Relation dialog box
The Edit Relation dialog box is where you will provide the specifics of the relationship. You will need to change the child element to the child table (in this case Invoice). Usually the dialog box will correctly select the foreign key field(s). If necessary, you can change the way that the Update rule, Delete rule, and Accept/Reject rule settings affect cascading changes to the DataSet. After you make these changes you should see something similar to what is shown in Figure 6.11.
Figure 6.11: The completed Edit Relation dialog box
After you click OK, you will see the Relation, as shown in Figure 6.12.
Now that we have our tables and the relationship set up, let's add an expression column to our Customer table. To add an expression column, go to the bottom of the Customer table and add a new row. Name it FullName and look at the properties for the column. Set the expression of the column to:
LastName + ', ' + FirstName
Figure 6.12: Our tables with a new relationship
Once you have done this, it should look like that shown in Figure 6.13.
Lastly, we need to add a unique constraint on Home Phone to make sure all of our customers' home phone numbers are unique. In the Typed DataSet vernacular, you will need to add a key to that column. Select the column, right-click on it, and select Add Key, as shown in Figure 6.14. This will launch the Edit Key dialog box, shown in Figure 6.15.
Figure 6.13: Adding an expression column
Figure 6.14: Selecting Add Key
Figure 6.15: Naming the key
If you do nothing but name the key and click OK, you've created a unique constraint. There may be cases in which you want to support having a multi-column unique key. To do this you would add fields to the key in the dialog box, as shown in Figure 6.16.
Figure 6.16: Supporting a multi-column unique key
This unique constraint will force the DataSet to make sure that all HomePhone and BusinessPhone combinations are unique. Congratulations, you now have your Typed DataSet defined.
Before we can see the code that Visual Studio .NET will generate, we need to build the project. After you build the project, your new Typed DataSet will be available for use.
6.2.2 Using XSD.exe to Create a Typed DataSet
Much like creating the class from Visual Studio .NET, Typed DataSets can also be created directly from an XML Schema Document (XSD) using the command-line XSD.exe tool that is included in the .NET Framework SDK. If you are not using Visual Studio .NET or just like your tools to be command-line tools, XSD.exe is for you. If you are using Visual Studio .NET, its built-in support for Typed DataSets is much easier than the tool and produces the same classes.
This tool is used to generate code from XML Schema Documentsboth classes derived from the .NET XML classes and those derived from the DataSet family of classes. Before we can start, we will need an XSD document. We can use the DataSet to create one of these for us, as in Listing 6.3.
Listing 6.3: Creating an XSD from a DataSet
... // Create a DataAdapter for each of the tables we're filling SqlDataAdapter daCustomers = new SqlDataAdapter("SELECT * FROM CUSTOMER", conn); // Create your blank DataSet DataSet dataSet = new DataSet(); // Fill the DataSet with each DataAdapter daCustomers.Fill(dataSet, "Customers"); // Grab our DataTable for simplicity DataTable customersTable = dataSet.Tables["Customers"]; // Improve the schema customersTable.Columns["CustomerID"].ReadOnly = true; customersTable.Columns["CustomerID"].Unique = true; customersTable.Columns["LastName"].MaxLength = 50; customersTable.Columns["LastName"].AllowDBNull = false; customersTable.Columns["FirstName"].MaxLength = 50; customersTable.Columns["FirstName"].AllowDBNull = false; customersTable.Columns["MiddleName"].MaxLength = 50; customersTable.Columns["State"].DefaultValue = "MA"; customersTable.Columns["State"].MaxLength = 2; customersTable.Columns["HomePhone"].Unique = true; // Write out our XSD file to use to generate our // typed DataSet dataSet.WriteXmlSchema(@"c:\CustomerDS.xsd");
Once we run this code, we will have a CustomersDS.xsd file to use with XSD.exe. To generate the class, simply go to the command line and use the XSD.exe tool, as shown in Figure 6.17.
Figure 6.17: Running the XSD.exe tool from the command line
The most interesting options are:
/d specifies to create a schema class that is of type DataSet. For Typed DataSet you will always specify this flag.
/l specifies the language in which to generate the classesCS is C#, VB is VB .NET and JS is Jscript .NET.
/n specifies the namespace to create our class in. This flag is optional.
/o specifies the output directory. If used, the output directory must already exist; the tool will not create it. If this is not specified, the classes will be created in the current directory.
Now you have your class file to include in your project.
6.2.3 Customizing the Generated Code with Annotations
ADO.NET allows you to control some aspects of the generated code by annotating the XSD that you use to generate the Typed DataSets. You can do this by annotating your XSD with several special attributes. All of these attributes are prefixed with the namespace of codegen. These attributes are:
typedName: Specifies the name of an object.
typedPlural: Specifies the name of the collection of objects.
typedParent: Specifies the name of the parent relationship.
typedChildren: Specifies the name of the child relationship.
nullValue: Specifies how to handle a DBNull value for a particular row value. When you use this annotation, there are several possible values for the nullValue attribute:
Replacement Value: The value to return instead of a null (for example, codegen:nullValue="" will return an empty string instead of a null for a string field).
_throw: Throws an exception when the value is accessed and is null (for example, codegen:nullValue=_throw). If the user would use the IsNull properties as part of the Typed DataSet to determine whether the field is null before trying to retrieve it. This is the default behavior if not annotated.
_null: Returns a null reference from the field. If a value type is encountered an exception is thrown.
_empty: Returns a reference created with an empty constructor. For strings, it returns String.Empty. For value types, an exception is thrown.
These must be added directly to the .XSD file. If you are using Visual Studio .NET, you must go to the XML view of your XSD to add these annotations. These annotations are added to an XSD like so:
<?xml version="1.0" encoding="utf-8" ?> <xs:schema id="AnnotatedTDS" targetNamespace="http://tempuri.org/AnnotatedTDS" elementFormDefault="qualified" attributeFormDefault="qualified" xmlns="http://tempuri.org/AnnotatedTDS" xmlns:mstns="http://tempuri.org/AnnotatedTDS" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:codegen="urn:schemas-microsoft-com:xml-msprop" > <xs:element name="AnnotatedTDS" msdata:IsDataSet="true"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="Customer" codegen:typedName="OurCustomer" codegen:typedPlural="OurCustomers"> ... <xs:element name="MiddleName" type="xs:string" minOccurs="0" codegen:nullValue="_empty" /> ... </xs:element> <xs:element name="Invoice" codegen:typedName="TheirInvoice" codegen:typedPlural="TheirInvoices"> ... <xs:element name="Terms" type="xs:string" minOccurs="0" codegen:nullValue="Net 30" /> ... </xs:element> </xs:choice> </xs:complexType> <xs:keyref name="CustomerInvoice" refer="ADONETKey1" msdata:AcceptRejectRule="Cascade" msdata:DeleteRule="Cascade" msdata:UpdateRule="Cascade" codegen:typedChildren="Invoices" codegen:typedParent="Customer"> <xs:selector xpath=".//mstns:Invoice" /> <xs:field xpath="mstns:CustomerID" /> </xs:keyref> ... </xs:element> </xs:schema>
Let's walk through this XSD and see where we have put the annotations.
The first thing we needed to do was to add the namespace reference to the schema header. This simply tells the XSD that we have a namespace defined and to allow the attributes.
Next, we make some changes to the Customer Element. typedName changes the name of the Typed DataRow in the DataTable to OurCustomer. When you ask for an individual row from the DataTable, it will return you an instance of the OurCustomer class instead of the default of Customer. typedPlural changes the name of the property on the DataSet that returns the specific DataTable. When retrieving the Customer DataTable, you would call the OurCustomers property.
Next, we added the codegen:nullValue="_empty" to the MiddleName element. This annotated our XSD so that a DBNull in the middle name element should be treated as an empty string in our generated Typed DataSet.
Next, we changed the Invoice element just like we did the Customer element. We renamed the Typed DataRow to TheirInvoice and the property that returns it to TheirInvoices.
Last, we changed the names of each end of our relationship by annotating the keydef tag with typedChildren and typedParent. This changes how each side of the relationship is named. The Customer class will have a method called Invoices (instead of GetInvoiceTable) to navigate down the relationship and the Invoice class will have a method called Customer (instead of GetCustomerTable) to navigate up the relationship.