Question

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?

Was it helpful?

Solution

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();
    }

OTHER TIPS

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(...);

This question and response popped up everywhere in google when searching for such a solution, so I thought I would put what worked [due to questions age, most likely an addition] for me in a more precise and succinct manner; "IsTable":

var configuration = Fluently.Configure()
    .Database(MsSqlConfiguration
    .MsSql2008
    ...
    .BuildConfiguration();

    var session = configuration.BuildSessionFactory().OpenSession();

    DatabaseMetadata meta = new DatabaseMetadata((DbConnection)session.Connection, new NHibernate.Dialect.MsSql2008Dialect());
    //TABLE_NAME e.g. "hibernate_unique_key"
        if (meta.IsTable("TABLE_NAME"))
        {
        ...

Hope that helps somebody because I implemented a convoluted strategy similar to the above before stumbling on this ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top