Sunday, June 7, 2009

Maintain Type using typed dataset..

Most of the applications when we need to deal with the datatypes for the values, we use class objects and pass it on to different layers. But if we need to handle this with XML, then we need to use typed dataset.
I have used a WCF service which will return the xml string as string to the client, which makes it compatible for any application to consume. The client need to know the datatype. The typed dataset helped me to get the datatypes of the xml returned from the service.
creating a typed dataset
public class MyDataSet : DataSet
public MyDataSet()
private void BuildTable()
DataTable table;

DataColumnCollection columns;
DataColumn dtCol;
this.DataSetName = "MyDataset";
table = new DataTable("Table");

columns = table.Columns;
dtCol = new DataColumn("col1", typeof(System.Char));

dtCol.ColumnMapping = MappingType.Attribute;

dtCol = new DataColumn("col2", typeof(System.Int16));
dtCol.ColumnMapping = MappingType.Attribute;

When we load the data from database to above dataset, the data will be tied with the datatype. When we get the xml from the dataset, this will return in below format

The same xml can be loaded to dataset as below

MyDataSet MDataSet = new MyDataSet();
MDataSet .ReadXml(new StringReader(xmlData));

The dataset will be loaded with the xml and retain the datatype which can be used on the client side. If the xml is loaded with Dataset object, the datatype will not be recognized and the data will be loaded as varchar.

No comments:

Post a Comment