tags:

views:

246

answers:

4

I know NHibernate is an ORM and it isn't normally used to create tables but I also know that NHibernate is able to create an entire database given some mappings.

I would like to know if there is an obscured API that I could use to dynamically create/alter/delete tables. I could do it with ADO.Net but I would like to abstract the code for creating tables for different databases (MS SQL, MySQL, etc.)

Precision 1: The problem with CreateSQLQuery is that I would have to rewrite the method for creating a table for different SQL servers (MS SQL, MySQl, etc.) It has no advantages over ADO.Net. When NHibernate generates the database from mappings it generates for any SQL servers... that is what I'm looking for. What is the code that is executed when NHibernate generates a database from mappings... is this code available/public?

A: 

There isn't a specific API to dynamically create/alter/delete tables. Depending on what you need to do and when you want these actions to happen you have the following options:

  • Use the tag in the xml mapping files to perform whatever action you want on the database just after your schema is generated
  • Use named queries and in the mapping files to create SQL statements to run from your code. (I have never tried these with create/alter/delete table commands but its worth to try).
  • Use the Session.CreateSQLQuery() method to execute a native SQL command. (Again as the previous option I have never tried it with create/alter/delete table commands but I believe its worth to try).
tolism7
Please read comment 1 that I added to my question for more details about what I'm looking for.
W3Max
A: 

Yes you can :)

You create dynamically a Type corresponding to the class to be mapped. And then generate a mapping.

The important classes to look in NH source code are in the Nhibernate.Mapping namespace : PersistentClass, RootClass.

Here is a sample : http://nhforge.org/blogs/nhibernate/archive/2008/11/16/mapping-source-how-map-a-class-without-use-nothing.aspx

I have used this "API" to generate dynamically Tables.

Matthieu
A: 

You could use the schema object.
You need to configure NHibernate and using the schema object call create. the two boolean values will either drop the database and recreate it or just output it to the console. VB.Net

Public Sub CreateDatabaseSchemaFromMappingFiles()
    Dim cfg As New NHibernate.Cfg.Configuration()

    cfg.Configure()

    Dim schema As New NHibernate.Tool.hbm2ddl.SchemaExport(cfg)

    schema.Create(True, False)
End Sub
Nathan Fisher
A: 

how you can use it in ado .net i have same problem but specifically need it for sqlserver 2005

abrar