Reputation: 562
I have inherited a .NET 2008 MVC application that uses nhibernate. The previous developer didn't get as far as generating a database for this project. I am fairly new to nhibernate, and I am trying to figure out what would be the optimal solution for creating a database script for creating a new database using the current mappings. I have gone through many posts on this site, but still do not understand completely how to get this to work. Any guidance is appreciated.
Thank you!
Upvotes: 5
Views: 4606
Reputation: 646
Assuming you have hbm.xml mappings and a valid nhibernate config file, you could write the following code in a console app to generate the SQL schema:
//load initial config from hibernate config file
Configuration cfg = new Configuration().Configure("hibernate.cfg.xml");
//add assembly in which the hbm.xml mappings are embedded (assuming Product class is in this assembly)
cfg.AddAssembly(typeof(Product).Assembly);
//this will generate the SQL schema file in the executable folder
new SchemaExport(cfg).SetOutputFile("schema.sql").Execute(true, false, false);
If you have fluent mappings, it should look more like this:
Fluently.Configure().Database(MsSqlConfiguration.MsSql2005).Mappings(
m => m.FluentMappings.AddFromAssemblyOf<Product>()).ExposeConfiguration(
config =>
{
new SchemaExport(config).SetOutputFile("schema.sql").Execute(true, false, false);
}).BuildConfiguration();
Upvotes: 7