Thursday, July 21, 2011

Converting Dataset to a C# model class

Problem statement: 

My Webservice is returning a dataset comprising of 1 table, which contains 135 columns. I need to build a model class (in C#), which should have all 110 column names as property name of the class.
Is there any way by which I can use the file stream writer & build my class?
Possible Solution:
Step 1: Convert your Dataset to a XML doc:
            var xmlSW = new System.IO.StreamWriter(@"c:\xml\Krishna.xml");
            myDataset.WriteXml(xmlSW, System.Data.XmlWriteMode.WriteSchema);
            xmlSW.Close();
Step 2: Convert your XML document to XSD doc.
   -> Open Visual Studio Command Promt.
   -> Type : xsd c:\xml\Krishna.xml (that is the path of the xml file.)
For Eg: C:\Windows\system32>xsd c:\xml\krishna.xml
Microsoft (R) Xml Schemas/DataTypes support utility [Microsoft (R) .NET Framework, Version 4.0.30319.1] Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\Windows\system32\krishna.xsd'.
Step 3: Convert your xsd to C# class.
   -> Open Visual Studio Command Promt.
   -> Type : xsd krishna.xsd /classes
For Eg: C:\Windows\system32>xsd krishna.xsd /classes
Microsoft (R) Xml Schemas/DataTypes support utility [Microsoft (R) .NET Framework, Version 4.0.30319.1] Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\Windows\system32\krishna.cs'.
NB: The generated property name can be renamed properly (if not proper) by Resharper or similar tools.
The output class file might contain some unnecessary information that u need to clean up. So this method is suitable if your dataset is returning huge tables containing hundreds of columns & you dont want to copy paste all of them manually to create your own mapping class.
Once you get the structure (class), you can use XmlSerializer to convert it to object or viceversa.

No comments: