Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Umbraco Migrations example
public class CustomMigrationEventHandler : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
// check target version
var rawTargetVersion = ConfigurationManager.AppSettings["app:MigrationVersion"] ?? "1.0.0";
var targetVersion = SemVersion.Parse(rawTargetVersion);
if (targetVersion != null)
{
HandleMigrations(targetVersion);
}
base.ApplicationStarted(umbracoApplication, applicationContext);
}
private void HandleMigrations(SemVersion targetVersion)
{
// get all migrations already executed
var currentVersion = new SemVersion(0, 0, 0);
var migrations = ApplicationContext.Current.Services.MigrationEntryService.GetAll(MigrationNames.MyCustomNamespace);
// get the latest migration executed
var latestMigration = migrations.OrderByDescending(x => x.Version).FirstOrDefault();
if (latestMigration != null)
{
currentVersion = latestMigration.Version;
}
if (targetVersion == currentVersion)
{
// nothing to do
return;
}
var migrationsRunner = new MigrationRunner(
ApplicationContext.Current.Services.MigrationEntryService,
ApplicationContext.Current.ProfilingLogger.Logger,
currentVersion,
targetVersion,
MigrationNames.MyCustomNamespace);
try
{
// run migrations
migrationsRunner.Execute(UmbracoContext.Current.Application.DatabaseContext.Database);
}
catch (Exception e)
{
LogHelper.Error<MigrationEvents>("Error running migration", e);
}
}
}
/// <summary>
/// MyCustomTable migration
/// </summary>
[Migration("1.0.0", 1, MigrationNames.MyCustomNamespace)]
public class MyCustomTableMigration : MigrationBase
{
private const string TableName = "MyCustomTable";
public MyCustomTableMigration(ISqlSyntaxProvider sqlSyntax, ILogger logger)
: base(sqlSyntax, logger)
{
}
/// <summary>
/// Process database upgrade
/// </summary>
public override void Up()
{
// create a new table if it doesn't exist
var tables = SqlSyntax.GetTablesInSchema(Context.Database).ToList();
if (!tables.InvariantContains(TableName))
{
Create.Table(TableName);
}
// or you can run alterations on existing tables
var columns = SqlSyntax.GetColumnsInSchema(Context.Database).ToArray();
var columnExists = columns.Any(x =>
string.Equals(x.TableName, tableName) &&
string.Equals(x.ColumnName, columnName)
);
if (!columnExists)
{
Alter.Table("SomeOtherTable").AddColumn("MyCustomString").AsString().Nullable();
}
}
/// <summary>
/// Process database downgrade
/// </summary>
public override void Down()
{
// drop the table
Delete.Table(TableName);
// remove the column from existing table
Delete.Column("MyCustomString").FromTable("SomeOtherTable");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.