We have SQLServer01.Publish.xml
when I double click this file and publish, it publishes a database to sqlServer01.
I wanted to ask can we publish this profile from code somehow ?
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
Where to get Microsoft.SqlServer.Dac
and so DacService
There are a couple of ways to get the Microsoft.SqlServer.Dac
library, either:
- Add the Nuget package
- Or install the SSDT tools on your dev machine, and then reference the DLL.
来源:https://stackoverflow.com/questions/34002580/how-do-i-publish-a-ssdt-database-from-code