从NHibernate生成数据库模式脚本。

时间:2021-06-06 12:58:26

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.

我继承了一个使用nhibernate的。net 2008 MVC应用程序。之前的开发人员并没有为这个项目生成一个数据库。我对nhibernate是相当陌生的,我正在试图找出创建一个使用当前映射创建新数据库的数据库脚本的最佳解决方案。我已经在这个网站上浏览了很多文章,但是仍然不完全理解如何让这个工作。任何指导是感激。

Thank you!

谢谢你!

1 个解决方案

#1


6  

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:

假设你有hbm。xml映射和有效的nhibernate配置文件,您可以在控制台应用程序中编写以下代码来生成SQL模式:

//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();

#1


6  

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:

假设你有hbm。xml映射和有效的nhibernate配置文件,您可以在控制台应用程序中编写以下代码来生成SQL模式:

//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();