This helped me a lot in restoring my database with the MDF file I had. A sample code which may help others to save as script file. Replace the method addTablesNode with the following code
```
private void addTablesNode(TreeNode rootNode)
{
var tableRootNode = rootNode.Nodes.Add("Tables");
var tables = db.Dmvs.Tables.OrderBy(t => t.Name);
foreach (var t in tables)
{
var tableNode = tableRootNode.Nodes.Add(t.Name);
tableNode.ContextMenu = tableMenu;
// Add columns
var tableColumnsNode = tableNode.Nodes.Add("Columns");
var columns = db.Dmvs.Columns
.Where(c => c.ObjectID == t.ObjectID)
.OrderBy(c => c.Name);
StringBuilder query = new StringBuilder();
query.Append("Create table " + t.Name + "(");
foreach (var c in columns)
{
var mainColumn = db.Dmvs.Columns.Where(x => x.ColumnID == c.ColumnID && x.ObjectID == c.ObjectID).Single();
var type = db.Dmvs.Types.Where(x => x.SystemTypeID == mainColumn.SystemTypeID).First();
if (type.Name != "int" && type.Name != "datetime" && type.Name != "bit")
tableColumnsNode.Nodes.Add(c.Name + " (" + type.Name + "[" + type.MaxLength + "])");
else
tableColumnsNode.Nodes.Add(c.Name + " (" + type.Name + ")");
query.Append(c.Name);
query.Append(" ");
query.Append(type.Name);
if (type.Name != "int" && type.Name != "datetime" && type.Name != "bit")
{
query.Append("(");
query.Append(type.MaxLength);
query.Append(")");
}
query.Append(",");
}
query = query.Remove(query.ToString().Length - 1, 1);
query.Append(")");
File.AppendAllText(string.Concat(t.Name, ".sql"), query.ToString());
// Add indexes
var tableIndexesNode = tableNode.Nodes.Add("Indexes");
var indexes = db.Dmvs.Indexes
.Where(i => i.ObjectID == t.ObjectID && i.IndexID > 0)
.OrderBy(i => i.Name);
foreach (var i in indexes)
{
var indexNode = tableIndexesNode.Nodes.Add(i.Name);
// Add index columns
var indexColumns = db.Dmvs.IndexColumns
.Where(ic => ic.ObjectID == t.ObjectID && ic.IndexID == i.IndexID);
foreach (var ic in indexColumns)
{
var mainColumn = db.Dmvs.Columns.Where(x => x.ColumnID == ic.ColumnID && x.ObjectID == ic.ObjectID).Single();
var type = db.Dmvs.Types.Where(x => x.SystemTypeID == mainColumn.SystemTypeID).First();
indexNode.Nodes.Add(columns.Where(c => c.ColumnID == ic.ColumnID).Single().Name + " (" + type.Name + "[" + type.MaxLength + "])");
}
}
}
}