Biki
Biki

Reputation: 2588

Converting Dataset to a model class

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 135 column names as property name of the class.

Is there any way by which I can use the filestream writer & build my class?

NB: I can easily convert the dataset to XML, but then I ve to do a lot of copy paste work to create the class manually. :(.

Upvotes: 1

Views: 2767

Answers (3)

Biki
Biki

Reputation: 2588

I got another approach as stated below:

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 returing 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.

Upvotes: 2

Neil Knight
Neil Knight

Reputation: 48537

I would recommend that you look into Scaffolding. You can download it here:

ASP.Net MVC Scaffold Generator

MVC Scaffold Generator is a CRUD code generator for the new ASP.NET MVC framework.

MVC Scaffold Generator allows you to quickly create the basic Add/Edit/Delete/List Asp.NET pages.

You can also watch a screencast here:

ASP.Net MVC Scaffold Generator screencast

Here is a Microsoft walkthrough:

Using MVC View Templates with Data Scaffolding

Upvotes: 0

Adam Houldsworth
Adam Houldsworth

Reputation: 64477

There are actually ways to convert XML into classes in C#:

http://sharpertutorials.com/using-xsd-tool-to-generate-classes-from-xml/

But if the XML is from default serialization of the dataset then it will probably look horrendous.

Upvotes: 1

Related Questions