Execute entity framework migration on a Linux

Executing entity framework migration on a Linux agent can be tricky. You cannot run simple dotnet ef command, because it doesn’t work on the Linux machine.

As always if you know what you are doing, you can go directly to the source, and download the pipeline here!

Before running the pipeline set below variables:

  buildConfiguration: 'Release'
  databaseContext: MyDatabaseContext
  azureSubscription: '' #connection name
  projectPath: $(Build.SourcesDirectory)/
  connectionString: "" #database connection string

So, in order to execute Entity framework migration on Linux, you must create a bundled script. This is a self-executing package for database migration. Let’s see, how to create a bundle:

- task: DotNetCoreCLI@2
displayName: Install EF Tool
  command: custom
  custom: 'tool'
  arguments: 'update --global dotnet-ef'                      
- task: DotNetCoreCLI@2
displayName: Create SQL Scripts
  command: custom
  custom: 'ef'
  arguments: 'migrations bundle --self-contained -r linux-x64 --no-build --output $(Build.ArtifactStagingDirectory)/ef/bundle --project $(projectPath) --context $(databaseContext) --configuration $(buildConfiguration)'           

First, you have to install the dotnet-ef tool. After this step succeeds, you can create a bundle. You need to specify for what target system, a bundle should be made. Additionally, a project path is needed as the name of the database context.

Take attention to the path where this handle is placed: $(Build.ArtifactStagingDirectory)/ef/bundle, you will need it in the deployment step.

When the bundle is ready, we can deploy changes to the database, this step covers the deployment of the bundle:

- task: AzureCLI@2
    azureSubscription: '$(azureSubscription)'
    scriptType: bash
    scriptLocation: inlineScript
    inlineScript: |
      chmod +x $(Pipeline.Workspace)/SQLScripts/bundle
      $(Pipeline.Workspace)/SQLScripts/bundle --connection "$(connectionString)"

The full pipeline for Azure DevOps can be found here!

I hope this article was useful for you 🙂 Check out more articles from this series:

Leave a Reply

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