views:

477

answers:

2

Whats the best, most consistent way to check if a table exists in NHibernate (or with Fluent-Nhibernate)?

Is it even possible? I mean it seems like a simple task for such a heavy-duty ORM.

Also on a related question, can you check if a set of tables or a whole schema exists with NHibernate?

+1  A: 

I looked in the source code for SchemaUpdate. I knew SchemaUpdate could detect a missing table and then generate a create script, rather than an update script. Sure enough, the answer was in there.

The GetTableMetadata function in NHibernate.Tool.hbm2ddl.DatabaseMetadata object will return null if a table does not exist in a database.

Normally, SchemaUpdate creates a DatabaseMetadata object and passes in into a Configuration object. But it looks like all you need to create a DatabaseMetadata is a DBConnection and Dialect object.

SchemaUpdate creates a DatabaseMetadata thusly:

connectionHelper.Prepare();
connection = connectionHelper.Connection;
meta = new DatabaseMetadata(connection, dialect);

NHibernate.Cfg.Configuration then calls

ITableMetadata tableInfo = databaseMetadata.GetTableMetadata(...);
Mark Rogers
+3  A: 

If you store you NHibernate configuration somewhere or do it before you build your session factory it is possible to validate the generated schema against the database.

    public void ValidateSchema(Configuration config)
    {
        new SchemaValidator(config).Validate();
    }
mhenrixon
Nice, I was looking for this sort of thing
Mark Rogers