How do I modify an existing database table (add/remove columns) with PetaPOCO (Umbraco 6, MVC)

StackOverflow https://stackoverflow.com/questions/18483015

Domanda

I have an Umbraco CMS application with some custom functionality for which I use PetaPOCO to store data in my database. I created my POCO and an Umbraco event that fires on application startup to create the table if it does not exist:

public class RegisterEvents : ApplicationEventHandler
{
    //This happens everytime the Umbraco Application starts
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        //Get the Umbraco Database context
        var db = applicationContext.DatabaseContext.Database;

        //Check if the DB table does NOT exist
        if (!db.TableExist("MyTable"))
        {
            //Create DB table - and set overwrite to false
            db.CreateTable<MyPetaPOCO>(false);
        }
    }
}

How do I modify the existing database (I want to add a column) without direct access to the database? I need to use code because the host doesn't provide access yet. I think I should be able to do this in this ApplicationStarted override event but I do not know how.

Edit

Should I use somethingl Fluent Migrator

È stato utile?

Soluzione 2

If you are using PetaPoco, you could use the db.Execute("alter table ...") but then you would need to have sufficient access rights to execute a DDL statement like that.

Also I would run this within a PetaPoco transaction too, as it's good practice.

Finally, if you were running this at Application_Start (which is fine) you would need to perform a check to ensure that the column didn't already exist.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top