[vNext] ASP.NET 5 Automatic Migrations with Fluent NHibernate

By | June 6, 2015

Advertisement from Google

vNextAs I said in the previous article, I am gonna tell you about Automatic migrations with NHibernate and Fluent NHibernate in ASP.NET 5 applications.

Automatic migrations is a really powerful feature, but you should be also really careful with it. Sometimes it might corrupt your schema or even data.

Now back to ASP.NET 5 and migrations. I have already explained how to install and configure Postgresql with NHibernate. To enable automatic migrations you need to modify configuration a bit:

private static ISessionFactory CreateSessionFactory()
{
    return Fluently
        .Configure()
            .Database(
                PostgreSQLConfiguration.PostgreSQL82
                .ConnectionString(c => 
                    c.Host("localhost")
                    .Port(5432)
                    .Database("test")
                    .Username("username")
                    .Password("password")))
            .Mappings(m => 
                m.AutoMappings.Add(
                    AutoMap
                        .AssemblyOf<User>()
                        .Where(t => typeof(Entity).IsAssignableFrom(t))
                        .UseOverridesFromAssemblyOf<ItemMapOverride>()
                        ))
            .ExposeConfiguration(TreatConfiguration)
        .BuildSessionFactory();
}

private static void TreatConfiguration(Configuration configuration)
{
    var update = new SchemaUpdate(configuration);
    update.Execute(false, true);
}

Advertisement from Google

To enable automatic migrations you just pass a delegate to the ExposeConfiguration method. In this delegate you need to use SchemaUpdate class.

You can also add additional logging, to track changes to a database:

private static void TreatConfiguration(Configuration configuration)
{
    var update = new SchemaUpdate(configuration);
    update.Execute(LogAutoMigration, true);
}

private static void LogAutoMigration(string sql)
{
    using (var file = new FileStream(@"update.sql", FileMode.Append))
    {
        using (var sw = new StreamWriter(file))
        {
            sw.Write(sql);
        }
    }
}

Now, every time you run your application SchemaUpdate will check existing database schema and compare it with your model, if automatic migration is not possible, it will throw an exception.

That’s all. Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *