当我双击此文件并发布时,我们有SQLServer01.Publish.xml
,它将数据库发布到sqlServer01。
我想问一下,我们能否以某种方式从代码中发布此配置文件?
SSDT似乎喜欢DacPac这种事情。在DacServices
有一个Microsoft.SqlServer.Dac
实用工具类。我认为这将要求在计划运行此代码的计算机上安装SSDT。
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:您可以使用Microsoft.Build.Evaluation.Project
命名空间来创建Project
对象并在本地构建它以进行集成测试,使用生成的构建的dacpac来初始化测试。
[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
}
}
参考文献:
Deborah's Developer MindScape: Deploying A DACPAC
哪里可以获得Microsoft.SqlServer.Dac
等DacService
有两种方法可以获得Microsoft.SqlServer.Dac
库: