如果这是一个包或您正在部署(或让其他人使用)的东西,您应该创建一个迁移并在您的 ApplicationStarted 方法中运行它。
https://cultiv.nl/blog/using-umbraco-migrations-to-deploy-changes/
上述文章中的示例:
要将列添加到现有 PetaPOCO DB:
创建一个从 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");
}
}
更新您ApplicationStarted
的逻辑以运行迁移:
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);
}
}
}
请注意,目标版本应与您在Migration
类属性中设置的版本相匹配(在本例中为 1.0.1)
当您进行更新并向应用程序或插件添加新功能时,您会创建新的迁移(如果需要)并更新目标版本。