从NHibernate生成数据库模式脚本

sso*_*l91 5 .net nhibernate asp.net-mvc nhibernate-mapping

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

谢谢!

Bre*_*tik 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);
Run Code Online (Sandbox Code Playgroud)

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

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

  • 基本上,在现有的visual studio解决方案中添加一个新的"控制台应用程序"项目.或者,您可以在现有应用程序启动时或在任何您喜欢的事件中添加这一堆代码. (2认同)