T4 Template for generate Table Script from XSD
The below T4 template will generate Create Table script from a XSD file. The Template will create a dataset from a XSD file and generate create table script from the dataset.
1 <#@ template language="C#v3.5" hostspecific="True" debug="True" #>
2 <#@ assembly name="System.Core" #>
3 <#@ assembly name="System.Data" #>
4 <#@ assembly name="System.Xml" #>
5 <#@ output extension=".sql" #>
6 <#@ import namespace="System" #>
7 <#@ import namespace="System.IO" #>
8 <#@ import namespace="System.Xml" #>
9 <#@ import namespace="System.Data" #>
10 <#PrepareToRender(); #>
11 <#
12 foreach (DataTable dt in ds.Tables) {
13 tableName= dt.ToString();
14 #>
15 CREATE TABLE <#= tableName #>
16 (
17 <#
18 PushIndent(" ");
19 foreach (DataColumn dc in dt.Columns) {
20 WriteLine( dc.ToString() + " " + MapToSqlType(dc.DataType.Name) + ",");
21 }
22 PopIndent();
23 #>
24 )
25 <#
26 }
27 #>
28 <#+
29 DataSet ds;
30 string tableName;
31 void PrepareToRender()
32 {
33 ds = new System.Data.DataSet();
34 //Load the XSD
35 ds.ReadXmlSchema("Metadata.xsd");
36 }
37 string MapToSqlType(string clrType)
38 {
39 switch(clrType)
40 {
41 case "String":
42 return "Varchar(50)";
43 case "Int32":
44 return "int";
45 //Do other mapings
46 default:
47 return clrType;
48 }
49 }
50 #>