Search code examples
asp.netnhibernateschemaexport

Can NHibernate check if the db schema has been generated?


So, newbie NHibernate user; trying to wrap my brain around it.

I'm contemplating how to handle deployment, and later injection of add-ons to a web app (which may require their own persistence classes).

I was thinking that using SchemaExport for the deployment would work pretty well, but I was wondering if there's a way too get NHibernate to tell me in a common, code-based way that a schema export has been done already, or not. Basically, I want to do smething like in this pseudocode:

  if(!_cfg.HasSchemaForType(typeof(MyType))
       ExportSchema(typeof(MyType));
  else
       UpdateSchema(typeof(MyType));

where the two functions would internally use SchemaExport or SchemaUpdate, respectively.


EDIT: Guys, I appreciate the answer so far, but they're missing the point a bit. What I'm trying to set up is a way for the application to allow for the addition and removal of add-ons which may require changes to the db. I'm not talking about versioning my own code or the like (at least, not as its primary function). So the question is less about when I deploy the app, and more about when I add or remove a plug-in. Has theis plugin (hence the pseudo-code type check) been deployed before? If so, run the update. If not, run the export. Make sense?


Solution

  • No, NHibernate doesn't do what you're asking. I imagine it would be possible to write some code that exported the schema and then compared it to the database schema. But it would probably be easier to export into a temporary database and use a 3rd party tool, such as redgate SQL Compare, to compare the schemas.

    Even if it did what you're asking, I don't see how that would help with deployment because its purpose is to create a database from scratch.

    Edited to add: Assuming each plugin has its own set of tables, you could determine if the schema has been deployed using one of several methods:

    • Attempt to load one of the plugin objects and catch the exception.
    • Examine the database schema (using SMO for SQL Server) to check if the table(s) exist.
    • Create a record in a table when a plugin is deployed.