Problem get Script from Database with .net Core 7

90 views Asked by At

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;
        }
    }
0

There are 0 answers