2013-06-20 39 views
5

我已經繼承了一個使用nhibernate的.NET 2008 MVC應用程序。以前的開發人員並沒有爲這個項目生成數據庫。 我對nhibernate相當陌生,我試圖找出創建數據庫腳本以創建使用當前映射的新數據庫的最佳解決方案。 我在這個網站上經歷了很多帖子,但仍然不完全明白如何讓這個工作。 任何指導表示讚賞。從NHibernate生成數據庫模式腳本

謝謝!

回答

6

假設你擁有的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(); 
+0

謝謝!我有流利的映射。當你說在控制檯應用程序中編寫代碼時,如何將該控制檯附加到我的解決方案?再次感謝! – ssokol91

+2

基本上,將新的「控制檯應用程序」項目添加到您現有的Visual Studio解決方案中。或者,您可以在現有應用程序啓動時或在任何您喜歡的事件中添加這一堆代碼。 – Bredstik

+0

太棒了!我注意到了「AddFromAssemblyOf 」這一行。我是否必須爲每個映射的類執行此操作,還是我沒有正確理解它? TKS! – ssokol91