54

I'm trying to figure out how to use NHibernate configuration with mapping to update table schemas, rather than dropping and recreating them.

Currently I'm using the NHibernate.Tool.hbm2ddl.SchemaExport obj with FluentNHibernate to generate the database schema for a mysql database. While I can't say it's a huge problem, whenever I call SchemaExport.Execute on the database, it's going to drop all the tables and then recreate them.

What would be way cooler is if I could just have it update the existing table structures retaining data where possible. But I don't really want to use a commerical product, or a code generator, because I don't like code generation in general, and I don't need this enough that I would consider paying for it. So hopefully any answer would keep these caveats in mind.

Mark Rogers
  • 96,497
  • 18
  • 85
  • 138

1 Answers1

67

The SchemaUpdate object provides database schema updating, by apparently generating and executing a series of SQL UPDATE statements (as well as constraint statements) when it's void Execute(bool script, bool doUpdate) function is called. The SchemaUpdate class is in the NHibernate.Tool.hbm2ddl namespace, which can be found in the Nhibernate.dll file.

SchemaUpdate is mentioned in chapter 15 of the nhibernate 1.0.2 toolset guide, here (section 15.1.5).

"The NHibernate FAQ" had (link now expired) a more complete example of how to use SchemaUpdate:

[Test]
public void Update_an_existing_database_schema()
{
    _cfg = new Configuration();
    _cfg.Configure();
    _cfg.AddAssembly(Assembly.LoadFrom("DataLayer.dll"));
    var update = new SchemaUpdate(_cfg);
    update.Execute(true, false);
}
Matt
  • 74,352
  • 26
  • 153
  • 180
Mark Rogers
  • 96,497
  • 18
  • 85
  • 138
  • 1
    we can't modify the setting of field once created for instance modify string length from nvarchar(255) to nvarchar(45), can we? – c.sokun Aug 31 '09 at 10:43
  • That's a good question, the create version of hbm2ddl would allows you to do this, but I've noticed sometimes I have to drop the tables before the create will run successfully. – Mark Rogers Aug 31 '09 at 13:54
  • This works brilliantly, this technique is also suited for Fluent NHibernate. – Contango Nov 29 '11 at 23:28
  • I can confirm that at least on SQL Server (and therefore on Azure), the fields are not updated, you have to manually do it. – Astaar Apr 03 '13 at 08:04
  • 2
    @Astaar: do you mean that changing from nvarchar(255) to nvarchar(45) doesn't work? or do you mean that schema update doesn't work at all? – Algoman Sep 04 '13 at 14:20