How do I publish a SSDT Database from code

五迷三道 提交于 2019-12-05 13:34:50
Ashtonian

SSDT seems to like DacPac for this kind of thing. There is a DacServices utility class in Microsoft.SqlServer.Dac. I think this will require SSDT to be installed on the machine you plan on running this code.

public class DacPacUtility
{
    public void DeployDacPac( string connString, string dacpacPath, string targetDbName )
    {
        var dbServices = new DacServices( connString );

        var dbPackage = DacPackage.Load( new FileStream( dacpacPath, FileMode.Open, FileAccess.Read ), DacSchemaModelStorageType.Memory, FileAccess.Read );

        var dbDeployOptions = new DacDeployOptions()
        {
            SqlCommandVariableValues =
            {
                new KeyValuePair< string, string >( "debug", "false" )
            },
            CreateNewDatabase = true,
            BlockOnPossibleDataLoss = false,
            BlockWhenDriftDetected = false
        };

        dbServices.Deploy( dbPackage, targetDbName, upgradeExisting : true, options : dbDeployOptions );
    }
}

Bonus: you can use the Microsoft.Build.Evaluation.Project namespace to new up a Project object and build it locally for integration testing using the resulting built dacpac to initialize a test.

[SetUpFixture]
public class TestSetup
{
    [SetUp]
    public void SetUpTests()
    {
        var projectPath = @"C:SomeDirectory";
        var project = new Project( projectPath );
        project.Build();
        ProjectCollection.GlobalProjectCollection.UnloadProject( project );

        var dacPac = new DacPacUtility();
        var connString = "Data Source=(localdb)\ProjectsV12;Initial Catalog=Tests;Integrated Security=True";
        var dacPacPath = projectPath + "..\bin\projectName.dacpac";
        dacPac.DeployDacPac(connString, dacPacPath, "Tests");
     }
     [TearDown]
     public void TearDownTests()
     {
       // TODO: delete db or run other cleanup scripts
     }
 }

References:

Deborah's Developer MindScape: Deploying A DACPAC

Latest SSDT

SSDT for VS 2010

Where to get Microsoft.SqlServer.Dac and so DacService

There are a couple of ways to get the Microsoft.SqlServer.Dac library, either:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!