I want to get a script from my database, but it gives the following error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Microsoft.SqlServer.Management.Smo.TableCollection.this[string].get returned null.
Code:
public static string DbGetScript(string connectionString, string databaseName, string filePath)
{
try
{
if (File.Exists(filePath))
File.Delete(filePath);
SqlConnection conn = new SqlConnection(connectionString);
ServerConnection serverConn = new ServerConnection(conn);
var server = new Server(serverConn);
var database = server.Databases[databaseName];
ScriptingOptions scriptOptions = new ScriptingOptions
{
FileName = filePath,
ScriptDrops = false,
ScriptData = true,
ScriptSchema = true,
IncludeIfNotExists = true,
ScriptForCreateDrop = true,
Encoding = Encoding.UTF8
};
string tbScr = "";
foreach (Table myTable in database.Tables)
{
database.Tables[myTable.Name].Script(scriptOptions);
// var tableScripts = myTable.Script(scriptOptions);
// foreach (string script in tableScripts)
// tbScr += script + "\n\n";
}
return filePath;
}
catch (Exception ex)
{
return "Error: " + ex.GetOriginalException().Message;
}
}