我在C#中使用SMO从数据库生成整个架构的脚本。
以下是我使用的代码:
// Instanciando
Server srv = new Server(con);
// Reference the database.
Database db = srv.Databases[ConfigurationManager.AppSettings["DB"].ToString()];
// Instanciando el scripteador
Scripter scrp = new Scripter(srv);
var urns = new List<Urn>();
// Propiedades del script
scrp.Options.IncludeHeaders = true;
scrp.Options.SchemaQualify = true;
scrp.Options.SchemaQualifyForeignKeysReferences = true;
scrp.Options.NoCollation = true;
scrp.Options.DriAllConstraints = true;
scrp.Options.DriAll = true;
scrp.Options.DriAllKeys = true;
scrp.Options.DriIndexes = true;
scrp.Options.ClusteredIndexes = true;
scrp.Options.NonClusteredIndexes = true;
scrp.Options.ToFileOnly = true;
// Obteniendo las tablas de la BD
foreach (Table tb in db.Tables)
{
// check if the table is not a system table
if(!tb.IsSystemObject)
{
urns.Add(tb.Urn);
}
}
// Instanciando un string builder para construir el script
StringBuilder builder = new StringBuilder();
System.Collections.Specialized.StringCollection sc = scrp.Script(urns.ToArray());
foreach (string st in sc)
{
// Agregando los comandos al string builder
builder.AppendLine(st);
builder.AppendLine("GO"); // Se coloca GO al final de cada statement
}
// Escribiendo el archivo
File.WriteAllText(path, builder.ToString());
问题是脚本是在没有任何约束的情况下生成的。 (FK,PK,UQ,CK)。
我做错了什么?
答案 0 :(得分:1)
尝试使用:
scrp.Options.EnforceScriptingOptions = true;
答案 1 :(得分:0)
使用这个脚本编写器选项我有我的约束:
Scripter CreateScrp = new Scripter(srv);
CreateScrp.Options.ScriptDrops = false; // Script drop statements
CreateScrp.Options.WithDependencies = true; // Walk dependencies
CreateScrp.Options.DriAllConstraints = true; // to include referential constraints in the script
CreateScrp.Options.Triggers = true; // Script triggers
CreateScrp.Options.NoCollation = false; // Use default collation
CreateScrp.Options.ExtendedProperties = true; // Script Extended Properties
CreateScrp.Options.SchemaQualify = true; // Qualify objects with schema names
CreateScrp.Options.ScriptSchema = true; // Script schema
CreateScrp.Options.IncludeDatabaseContext = true;
CreateScrp.Options.EnforceScriptingOptions = true;
CreateScrp.ScriptingProgress += CreateScrp_ScriptingProgress;
虽然^^
,但不确定您缺少哪一个