流利的NHibernate - 只有在不存在的情况下才创建数据库模式 [英] Fluent NHibernate - Create database schema only if not existing

查看:107
本文介绍了流利的NHibernate - 只有在不存在的情况下才创建数据库模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我用Fluent Nhibernate来创建我的数据库。到目前为止,我一直在重新创建数据库模式。这样做的代码是这样的:
$ b $ pre $ 公共NhibernateSessionFactory(IPersistenceConfigurer配置)
{
_sessionFactory =流利。配置()。
数据库(config)。
映射(m => m.FluentMappings.AddFromAssemblyOf< MappingsPersistenceModel>())。
ExposeConfiguration(BuildSchema)。
BuildSessionFactory();


private static void BuildSchema(Configuration config)
{
// if(DbExists(config))
// return;

新建SchemaExport(config).Create(false,true);

$ / code>

请注意 if(DbExists(config)) 。这是我想要做的。我只想创建模式,如果它实际上不存在。在下一步 - 我想更新
它将被创建,如果它不是最新的。

我如何实现这个目标?我期待一个 config.DatabaseExists(),但我看不到任何这样的事情。我看到一些解决办法的可能性,但是处理这个问题的典型推荐方法是什么?

解决方案

您可以直接使用 SchemaUpdate 如果它存在并创建它,如果它不存在:

pre $公共NhibernateSessionFactory(IPersistenceConfigurer配置)
{
_sessionFactory =流利的.Configure()。
数据库(config)。
映射(m => m.FluentMappings.AddFromAssemblyOf< MappingsPersistenceModel>())。
ExposeConfiguration(cfg =>新的SchemaUpdate(cfg).Execute(false,true))。
BuildSessionFactory();

$ / code>

一个提示: SchemaUpdate 不会执行破坏性更新(删除表,列等)。它只会添加它们。


I have an application where I use Fluent Nhibernate to create my database. This far I've been recreating the database schema each time. The code that does this is this:

public NhibernateSessionFactory(IPersistenceConfigurer config)
{
    _sessionFactory = Fluently.Configure().
        Database(config).
        Mappings(m => m.FluentMappings.AddFromAssemblyOf<MappingsPersistenceModel>()).
        ExposeConfiguration(BuildSchema).
        BuildSessionFactory();
}

private static void BuildSchema(Configuration config)
{
    // if (DbExists(config))
    //    return; 

    new SchemaExport(config).Create(false, true);
}

Note the "if (DbExists(config))". This is what I'd like to do. I'd like to create the schema only if it actually doesn't already exist. And in the next step - I'd like to update it to be created if it isn't up to date.

How do I achieve this? I am expecting a config.DatabaseExists(), but I can't see anything like this. I see some possibilities of a hacky solution, but what is the typical recommended way of handling this?

解决方案

You can just use SchemaUpdate instead, it will update the schema if it exists and create it if it does not:

public NhibernateSessionFactory(IPersistenceConfigurer config)
{
    _sessionFactory = Fluently.Configure().
        Database(config).
        Mappings(m => m.FluentMappings.AddFromAssemblyOf<MappingsPersistenceModel>()).
        ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true)).
        BuildSessionFactory();
}

One caveat: SchemaUpdate does not do destructive updates (dropping tables, columns, etc.). It will only add them.

这篇关于流利的NHibernate - 只有在不存在的情况下才创建数据库模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆