5

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!

0

1 Answer 1

7

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();
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I have fluent mappings. When you are saying write a code in a console app, how to I attach that console to my solution? Thanks again for this!
Basically, add a new "Console Application" project to your existing visual studio solution. Or you could add this bunch of code at the startup of your existing app or in an event, wherever you like.
That's great! I have noticed the line "AddFromAssemblyOf<Product>". Do I have to do this for every mapped class, or am I not understanding it properly? Tks!
Assuming all you fluent mappings are in the same assembly, you only have to specify one of the class inside that assembly. It will automatically scan for all mappings inside that assembly based on the type your provide.
I have added the code right after nhibernate session gets initialize. The code runs fine, but the schema.sql is coming up blank. Any ideas? Tks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.