How do you check if a table exists with NHibernate(or Fluent)?
Asked Answered
T

3

5

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?

Threonine answered 12/10, 2009 at 21:22 Comment(2)
Are you looking to check it against your mapping?Telephonist
either way, I want to see if the physical table exists.Threonine
P
12

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();
    }
Pleopod answered 14/10, 2009 at 19:10 Comment(1)
Nice, I was looking for this sort of thingThreonine
T
3

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(...);
Threonine answered 13/10, 2009 at 1:50 Comment(0)
T
3

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

Twylatwyman answered 29/7, 2015 at 3:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.