从NHibernate生成数据库模式脚本

时间:2013-06-20 17:35:47

标签: .net asp.net-mvc nhibernate nhibernate-mapping

我继承了一个使用nhibernate的.NET 2008 MVC应用程序。以前的开发人员没有为这个项目生成数据库。 我对nhibernate相当新,我试图找出使用当前映射创建数据库脚本以创建新数据库的最佳解决方案。 我在这个网站上经历了很多帖子,但仍然完全不明白如何让这个工作。 任何指导都表示赞赏。

谢谢!

1 个答案:

答案 0 :(得分:7)

假设您有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);

如果你有流畅的映射,它看起来应该更像:

Fluently.Configure().Database(MsSqlConfiguration.MsSql2005).Mappings(
            m => m.FluentMappings.AddFromAssemblyOf<Product>()).ExposeConfiguration(
                config =>
                    {
                        new SchemaExport(config).SetOutputFile("schema.sql").Execute(true, false, false);
                    }).BuildConfiguration();