If this is a package or something that you are deploying (or are having others consume), you should create a migration and run it in your ApplicationStarted method.
https://cultiv.nl/blog/using-umbraco-migrations-to-deploy-changes/
Example from the above article:
In order to add a column to an existing PetaPOCO DB:
Create a migration class that derives from MigrationBase:
[Migration("1.0.1", 1, "YourTableName")]
public class AddNewColumnToTable : MigrationBase
{
public AddNewColumnToTable(ISqlSyntaxProvider sqlSyntax, ILogger logger)
: base(sqlSyntax, logger)
{ }
public override void Up()
{
Alter.Table("YourTableName").AddColumn("ColumnToAdd").AsString().Nullable();
}
public override void Down()
{
Delete.Column("ColumnToAdd").FromTable("YourTableName");
}
}
Update your ApplicationStarted
with logic to run the migration:
public class MyApplication : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
HandleStatisticsMigration();
}
private static void HandleStatisticsMigration()
{
const string productName = "YourTableName";
var currentVersion = new SemVersion(0, 0, 0);
// get all migrations for "YourTableName" already executed
var migrations = ApplicationContext.Current.Services.MigrationEntryService.GetAll(productName);
// get the latest migration for "YourTableName" executed
var latestMigration = migrations.OrderByDescending(x => x.Version).FirstOrDefault();
if (latestMigration != null)
currentVersion = latestMigration.Version;
var targetVersion = new SemVersion(1, 0, 1);
if (targetVersion == currentVersion)
return;
var migrationsRunner = new MigrationRunner(
ApplicationContext.Current.Services.MigrationEntryService,
ApplicationContext.Current.ProfilingLogger.Logger,
currentVersion,
targetVersion,
productName);
try
{
migrationsRunner.Execute(UmbracoContext.Current.Application.DatabaseContext.Database);
}
catch (Exception e)
{
LogHelper.Error<MyApplication>("Error running YourTableName migration", e);
}
}
}
Note that the target version should match the version you set in your Migration
class attribute (in this example, 1.0.1)
As you make updates and add new functionality to your application or plugin, you create new migrations (if needed), and update your target version.