Update-Database MSI Custom Action

In the Prevent EF Migrations from Creating or Changing the Database post I showed how to prevent the application from automatically creating or updating the database. Instead I want the installation program to do that. With a Web Setup Project for the installation an MSI Custom Action is needed.

The actual work of updating the database is done by the migrate.exe tool. To make the MSI package run it properly turned out to be a bit of a challenge. I first included migrate.exe in the installation package to have it deployed to the bin directory together with the assemblies of the system. There is support for running an exe file as a custom action in the web setup projects. Ufortunately I couldn’t get migrate.exe to work unless the working directory was set to the bin directory. The working directory for custom actions is c:\windows\system32 by default. To handle that, a small vb-script was used.

The script gets some configuration that is passed as custom action data from the msi package. Then it sets the current directory and executes migrate.exe.

Option explicit
 
dim customActionData
customActionData = Session.Property("CustomActionData")
 
dim dataParts, path, assembly, config
dataParts = split(customActionData, ";")
path = dataParts(0)
assembly = dataParts(1)
config = dataParts(2)
 
dim shell
Set shell = CreateObject("WScript.Shell")
shell.CurrentDirectory = path
 
dim commandLine
commandLine = "migrate " + assembly + _
  " /StartupConfigurationFile:" + config
 
shell.Run commandLine, 1, true
 
set shell = nothing

Save the script in a file (e.g. update-database.vbs) and include it in the web setup project, to be deployed to the bin directory. Then setup a custom action in the Commit section to run the script.

The script expects a CustomActionData string with three parts.

  • The path of migrate.exe and the assembly containing the migrations (it has to be the same directory).
  • The name of the assembly with the migrations.
  • The config file to read the connection string from.

The special string [TARGETDIR] will be expanded to the installation directory (including a trailing \) by MSI before passing the string to the custom action.

This post is part of the EF Migrations series.<< EF Code First Navigation Properties and Foreign Keys

1 comment

  1. Beware that some antivirus programs silently eats VBS-scripts in MSI-installers.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.