5

I read xsd and xml file in DataSet, now I want create db from this DataSet

foreach (DataTable dt in temp.Tables) {
    foreach (DataColumn dc in dt.Columns) {
        //example for one column
        SqlCommand createtable = new SqlCommand(
            "create table " + dt.TableName + " (" 
            + dc.ColumnName + "  varchar(max))", conn);
        createtable.ExecuteNonQuery();
    }
}

But I have some problem, when I create db table I need column type and size from XSD (in example use varchar(max)). How to fix this?

For example in xsd I have

<xs:restriction base="xs:string">
<xs:maxLength value="36"/>
<xs:minLength value="1"/>
</xs:restriction>

or

<xs:restriction base="xs:string">
<xs:maxLength value="40"/>
</xs:restriction>

or

<xs:restriction base="xs:decimal">
<xs:totalDigits value="19"/>
<xs:fractionDigits value="2"/>
</xs:restriction>

In the end I need script to create db tables with size of columns (like in xsd)

UPD: Maybe use XmlSchemaSet to parse XSD?

13
  • 1
    Walk over the DataColumn(s) of the Columns Property of the DataTable and create the approriate column definitions. Commented Jun 1, 2015 at 11:48
  • 1
    I don't understand what you mean Commented Jun 1, 2015 at 11:53
  • 2
    Check this MSDN article ;). Commented Jun 1, 2015 at 11:56
  • 2
    You should import the XML directly into SQL Server to create new database. No need to use a C# application. Try this : stackoverflow.com/questions/2628327/… Commented Jun 1, 2015 at 12:08
  • 2
    you can get the data type, max length and probably a lot more information from the dataset columns... Commented Jun 4, 2015 at 12:17

3 Answers 3

4
+25

use XSD2DB

XSD2DB is a command line tool written in C#, that will read a Microsoft ADO.NET compatible DataSet Schema File (XSD) and generate a database.

link

Sign up to request clarification or add additional context in comments.

Comments

1

Would scaffolding be able to help you in this situation?

Maybe take a look at that, I know there was a way of doing a reverse engeneering of the database first with scaffolding

Comments

1

I guess there's no general solution to this. An XSD can easily describe something that does not map to a relational database.While you can try to "automate" this, your XSD's must be designed with a relational database in mind, or it won't work out well.

However you can transfer your datatables in memory to sql server database using SQLServer Management Objects and SqlBulkCopy.

Please refer to this link for more information. Hope this may help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.