【问题标题】:Generating Database Schema Script from NHibernate从 NHibernate 生成数据库模式脚本
【发布时间】:2013-06-21 04:01:56
【问题描述】:

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

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢!我有流畅的映射。当您说在控制台应用程序中编写代码时,如何将该控制台附加到我的解决方案?再次感谢!
    • 基本上,将一个新的“控制台应用程序”项目添加到您现有的 Visual Studio 解决方案中。或者,您可以在现有应用程序启动时或在任何您喜欢的活动中添加这组代码。
    • 太好了!我注意到“AddFromAssemblyOf”这一行。我是否必须为每个映射的类都这样做,还是我没有正确理解它?谢了!
    • 假设所有流畅的映射都在同一个程序集中,您只需指定该程序集中的一个类。它将根据您提供的类型自动扫描该程序集中的所有映射。
    • 我在 nhibernate 会话初始化后添加了代码。代码运行良好,但 schema.sql 出现空白。有任何想法吗?谢了!
    猜你喜欢
    • 2010-11-20
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 2013-10-23
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    相关资源
    最近更新 更多