Search code examples
nhibernatedatabase-migration

"Migrate" database with NHibernate


I have a program using NHibernate, recently we have made an update to the database model, we have added a table. Now we use SQLite to sync parts of the "central" database to enable a offline support in the program. It is now the problems start arising... When a user have an updated version of the program, but an old version of the database NHibernate wont work properly.

So I would like to "migrate" the database to the new schema. I have testet with SchemaExport, but that clears the database of all it's data. Do I have to manually create the table?

Also, I only notice this when I try to access a lacy loaded property in my database, is there anyway to see if the model correlates with the database schema?


Solution

  • Use SchemaUpdate instead.

    It will check your current schema with mapping files. If any changes in mapping files (table added as you said) will be reflected to underlying RDBMS. A DDL will be automatically generated by NHibernate and will be executed to match the changes.

    Sample code is something like below:

    SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
    schemaUpdate.Execute(false, true);
    

    Depending on your need, you may play with two parameters of Execute -- self explanatory.