Data Sets and Tables

One of the most common types of data contract exchanged between clients and services involves data that originates in or is destined for a database. In .NET, a common way of interacting with databases is via ADO.NET's data set and data table types. Applications can use the raw DataSet and DataTable types, or use the data access management tools in Visual Studio 2008 to generate type-safe derivatives.

The raw DataSet and DataTable types are serializable (i.e., marked with the Serializable attribute):

[Serializable]
public class DataSet : ...
{...}

[Serializable]
public class DataTable : ...
{...}

This means that you can define valid service contracts that accept or return data tables or data sets:

[DataContract]
struct Contact
{...}

[ServiceContract]
interface IContactManager
{
   [OperationContract]
   void AddContact(Contact contact);

   [OperationContract]
   void AddContacts(DataTable contacts);

   [OperationContract]
   DataTable GetContacts(  );
}

You can also use the type-safe subclasses of DataSet and DataTable in your contracts. For example, suppose in your database you have a table called Contacts that contains your contacts, with columns such as FirstName and LastName. You can use Visual Studio 2008 to generate a type-safe data set called MyDataSet that has a nested class called ContactsDataTable, as well as a type-safe row and type-safe data adapter, as shown in Example 3-10.

Example 3-10. Type-safe data set and data table

[Serializable] public partial class MyDataSet : DataSet ...

Get Programming WCF Services, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.