SSDT如何从DACPAC文件创建新数据库?

时间:2017-07-20 12:28:54

标签: c# sql-server-data-tools dacpac schema-compare sqlpackage

目前使用SqlPackage.exe cmd行工具生成脚本,方法是将DacPac文件与目标数据库进行比较。这将是Create the database if it doesn't already exist

我们现在想要将其切换为使用Microsoft.Data.Tools.Msbuild Nuget包(使用C#进行部署),但是当数据库容器不存在时,使用SchemaComparison进行比较将失败。似乎没有太多与该软件包相关的文档。

是否有任何工具作为此包的一部分,这将允许我在比较之前创建一个空的数据库容器?

我目前正在使用以下代码(在与现有数据库进行比较时有效):

 SchemaCompareDacpacEndpoint sourceDacpac = new SchemaCompareDacpacEndpoint(@"C:\DeployDB.dacpac");

        SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
        csb.DataSource = @".";
        csb.InitialCatalog = "DeployTestDB";
        csb.IntegratedSecurity = true;
        SchemaCompareDatabaseEndpoint targetDatabase = new SchemaCompareDatabaseEndpoint(csb.ToString());


        SchemaComparison comparison = new SchemaComparison(sourceDacpac, targetDatabase);
        comparison.Options.DropObjectsNotInSource = true;
        comparison.Options.BlockOnPossibleDataLoss = false;
        comparison.Options.TreatVerificationErrorsAsWarnings = true;
        comparison.Options.ScriptDatabaseOptions = true;
        comparison.Options.GenerateSmartDefaults = true;

        SchemaComparisonResult comparisonResult = comparison.Compare();

此时,ComparisonResult有一条错误消息: {错误SQL0:无法打开数据库" DeployTestDB"登录请求。登录失败。用户' myUsername'。}

登录失败

1 个答案:

答案 0 :(得分:1)

查看Microsoft.SqlServer.Dac.dll中的DacServices类。

代码看起来像这样:

using Microsoft.SqlServer.Dac;

class Program
{
    static void Main(string[] args)
    {
        DacServices ds = new DacServices(@"Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=true");
        using (DacPackage dp = DacPackage.Load(@"C:\temp\mydb.dacpac"))
        {
            ds.Deploy(dp, @"DATABASENAME", upgradeExisting: false, options: null, cancellationToken: null);
        }
    }
}