tags:

views:

35

answers:

1

When using an ORM (specifically NHibernate), how is refactoring of data handled? I mean, if data objects change such that the underlying relational DB schema changes, does the ORM offer any help in schema upgrades / downgrades in the DB? How about migration of existing data to the new schema?

I am in the process of making a decision on using an ORM and have very limited exposure. Please bear with me if the questions are naive.

+7  A: 

In NHibernate, you can use the SchemaUpdate class to make additive changes to your schema. (Additive changes would include new tables, new columns, etc., but not deletes.) SchemaUpdate is intended for development purposes and is not intended to be run in production. I would strongly recommend checking out a SQL migration tool such as Tarantino, dbdeploy.net, RikMigrations, or similar.

Migration tools come in two flavours - SQL script-based (Tarantino and dbdeploy.net) and code-based (RikMigrations and Rails-style migrations). With a code-based migration tool, you write your migrations using code written in C#, VB, Ruby, ... SQL script-based tools take an ordered set of SQL scripts. In either case the migration tool runs any migrations against your database that haven't been run before. (Typically a migrations table lists the scripts that have been run and allows the tool to figure out which still need to be run.) The SQL scripts are generated via:

// SchemaUpdate.Execute(bool script, bool doUpdate)
new SchemaUpdate(cfg).Execute(true, false); 

and then edited to taste. Or you could generate a new schema using NHibernate's SchemaExport and using a schema diff tool such as Microsoft Visual Studio for Database Professionals Ultimate Now With Extra Mayo Edition (aka DataDude) or RedGate SQL Compare. You would need to write transformation scripts by hand as there is no way in general for the SQL migration tool to know that that Foo char(1) column filled with T/F should be transformed into that Bar bit column.

Personally I prefer the SQL script-based migration tools as I can generate the schema diffs using a tool and then edit to taste rather than having to hand-roll the entire migration using C# or similar language.

James Kovacs
+1 for an excellent reply.
afsharm