Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

.net - Fluent NHibernate - Create database schema only if not existing

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?

question from:https://stackoverflow.com/questions/5884359/fluent-nhibernate-create-database-schema-only-if-not-existing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...