Lesser-Known NHibernate Features – Generating Database Scripts
As you may know, NHibernate knows how to generate the database for you from its model. Any of the supported databases will do.
What you may not know is that you can simply generate the SQL scripts that would be used to either generate the database from scratch or just update it to match the model as it is. For that you use the SchemaExport and SchemaValidator classes.
SchemaValidator takes a Configuration instance and basically throws an exception if, when its Validate method is called, the database does not match the model.
SchemaExport has far more options; it can:
- Create or drop a database model based on the entity model;
- Output the SQL to a file, either executing it at the same time or not;
- Execute the SQL to another arbitrary database connection;
- Execute a custom action after each line of the generated SQL script.
An example:
1: var validator = new SchemaValidator(cfg);
2:
3: try
4: {
5: validator.Validate();
6: }
7: catch
8: {
9: var export = new SchemaExport(cfg).SetOutputFile("Script.sql");
10:
11: //send the script to standard output and execute it
12: export.Execute(useStdOut: true, execute: true, justDrop: false);
13: //or
14: //send all lines of the script to the System.Console.WriteLine method
15: export.Execute(scriptAction: System.Console.WriteLine, execute: false, justDrop: false);
16: }