Computer Magic Logo
Tables creation

Sunday, August 23, 2015

Published by Aristotelis Pitaridis

With PetaPoco we can automatically generate the tables in the database using the Models that we defined. Of course we could create the tables manually but in case that we want to automate a procedure we will see how to do it.

We could create the tables in the constructor of the repository class that we will create but this will have as a result every time that we try to access or modify the contents of the table to check if the table exists. We can make this check once when our application starts which will be better. In order to do it we are going to hook into the ApplicationStarted event of the Umbraco CMS startup events.

We create a class called PetaPocoApplicationEventHandler and we save the file at the location "~/App_Code/ComputerMagic/PetaPoco/PetaPocoApplicationEventHandler.cs".

using ComputerMagic.PetaPoco.Models;
using Umbraco.Core;
using Umbraco.Core.Persistence;

namespace ComputerMagic.PetaPoco
{
    public class PetaPocoApplicationEventHandler : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            var db = applicationContext.DatabaseContext.Database;

            if (!db.TableExist("CMAuthors"))
            {
                db.CreateTable<Author>(false);
            }

            if (!db.TableExist("CMBooks"))
            {
                db.CreateTable<Book>(false);
            }
        }
    }
}

We created a class which inherits from the ApplicationEventHandler and we override the ApplicationStarted member function which will be executed when the Umbraco application will start. Inside this member function we get the database context and we check if each of the two tables exists and in case that they do not exist we use the CreateTable member function of the database context in order to create them.

Now when we try to view a page of our Umbraco installation which will have as a result the ApplicationEventHandler will execute the required code and the tables will be ready to use.

As we can see in the picture above the tables has been created and all the required features has been assigned to the columns of the tables.