使用 VSTS 的 Build (CI) 建立 LocalDB 以供測試

當測試專案有時候需要用到 DB 來測試,
在本地端的時候可以用 LocalDB,那麼使用 VSTS 做持續部屬的時候該怎麼測試呢?
答案就是在 VSTS 建置專案的 VM 上安裝 LocalDB,並使用 dacpac 檔部屬資料庫。

關鍵只有一個,就是執行 powershell 做這件事,
參考Deploy dacpac with Powershell on Build vNext 稍作改良,
並將說明註解如下:

#
# Powershell script that deploys the dacpac to (localdb)\MSSQLLocalDB that the integration tests can run against.
#

$dbname = "我的DB名稱"
$dacpacname = "我的部屬檔案.dacpac"

# 找尋部屬檔,gci 功能就是 dos command 的 dir,
$dacpac = gci -Recurse -Filter "$dacpacname" -ErrorAction SilentlyContinue | Select -First 1

# 載入 Microsoft.SqlServer.Dac.dll,在目前版本中可以在下面位置找到
add-type -path "C:\Program Files\Microsoft SQL Server\140\DAC\bin\Microsoft.SqlServer.Dac.dll"

# Create a DacServices object, which needs a connection string 
# The (localdb)\ProjectsV12 instance is created by SQL Server Data Tools (SSDT) and should not be used by applications
# (localdb)\MSSQLLocalDB is the SQL Server 2014 LocalDB default instance name
# (localdb)\v11.0 is the SQL Server 2012 LocalDB default instance name
$dacServices = New-Object Microsoft.SqlServer.Dac.DacServices "Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True;Pooling=False"

# Options
$deployOptions = New-Object Microsoft.SqlServer.Dac.DacDeployOptions
$deployOptions.CreateNewDatabase = $true
$deployOptions.BlockOnPossibleDataLoss = $false
$deployOptions.BlockWhenDriftDetected = $false
# Must specify variables if there are any defined!
$deployOptions.SqlCommandVariableValues.Add("Environment", "dev")

# register event. For info on this cmdlet, see http://technet.microsoft.com/en-us/library/hh849929.aspx 
Register-ObjectEvent -InputObject $dacServices -EventName "Message" -Action { Write-Host $EventArgs.Message.Message } | Out-Null
 
# Load dacpac from file & deploy database
$dp = [Microsoft.SqlServer.Dac.DacPackage]::Load($dacpac.FullName) 
$dacServices.Deploy($dp, $dbname, $true, $deployOptions)

將此 ps 放在 test 之前,

以後在建置專案時,就可以讓測試專案也有 DB 可以用了