Skip to content

How to run migration from .NET Core Console Application

Rodel E. Dagumampan edited this page Feb 11, 2020 · 4 revisions

Run your database migration when Console App starts. This ensures that database is always at latest compatible state before operating the service. This is made using Yuniql.Core nuget package. Package can be used for Worker and WebApp services.

Pre-requisites

Prepare your database

Deploy an SQL Server on Linux container or use your preferred instance.

docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=P@ssw0rd!" -p 1400:1433 -d mcr.microsoft.com/mssql/server:2017-latest

Run migration from .NET Core console app

Create new web app

dotnet --version
3.0.100

dotnet new console -o console-sample
cd console-sample

Add Yuniql.AspNetCore

dotnet add package Yuniql.Core
dotnet build

Copy sample database into _db directory in your project

git clone https://github.com/rdagumampan/yuniql.git c:\temp\yuniql-console
cd c:\temp\yuniql-console\samples\basic-sqlserver-sample

Modify the Main method of Program.cs

using Yuniql.Core;
...
...

static void Main(string[] args)
{
	var traceService = new ConsoleTraceService { IsDebugEnabled = true };
	var configuration = new YuniqlConfiguration
	{
		WorkspacePath = Path.Combine(Environment.CurrentDirectory, "_db"),
		ConnectionString = "Server=localhost,1400;Database=yuniqldb;User Id=SA;Password=P@ssw0rd!",
		AutoCreateDatabase = true
	};

	var migrationServiceFactory = new MigrationServiceFactory(traceService);
	var migrationService = migrationServiceFactory.Create();
	migrationService.Initialize(configuration.ConnectionString);
	migrationService.Run(
		configuration.WorkspacePath,
		configuration.TargetVersion,
		configuration.AutoCreateDatabase,
		configuration.Tokens,
		configuration.VerifyOnly,
		configuration.Delimiter);
}

Test run

dotnet build
dotnet run --debug

Found bugs?

Help us improve further please create an issue.