9

I've been following some examples about how to use NHibernate with SQLite, and most of them are related to unit testing database CRUD operations and all that. So, the examples I've googled and followed so far are all related to that. Which is nice, but the problem is that everytime I run my program the database is created anew! How can I modify my code so that if the database already exists NHibernate does NOT create it? And yes, I've tried to check with File.Exists, but it's ignored; I believe because NHibernate gets to the file first.

This is my mapping:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory name="NHibernate.Test">
    <property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property>
    <property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
    <property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
    <property name="query.substitutions">true=1;false=0</property>
    <property name="show_sql">false</property>
  </session-factory>
</hibernate-configuration>

And my full code:

using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using NHibernate;
using NHibernate.Cfg;
using PruebaNHLite.Domain;

namespace PruebaNHLite
{
    public class Program
    {
        public static ISession sess;
        public static Configuration cfg;
        public static SQLiteConnection connection;
        private const string CONNECTION_STRING = 
                @"Data Source=nhlite.db;Pooling=true;FailIfMissing=false;
                                BinaryGUID=false;New=false;Compress=true;Version=3";

        static void Main(string[] args)
        {
            Init();
            BuildSchema();
            Insert();
            Retrieve();
            sess.Close();
            sess = null;
        }

        public static void Init()
        {
            // Initialize NHibernate
            cfg = new Configuration();
            cfg.Configure();
            IDictionary<string, string> props = new Dictionary<string, string>();
            props.Add("connection.connection_string", CONNECTION_STRING);
            props.Add("connection.driver_class", "NHibernate.Driver.SQLite20Driver");
            props.Add("dialect", "NHibernate.Dialect.SQLiteDialect");
            props.Add("proxyfactory.factory_class", "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu");
            props.Add("query.substitutions", "true=1;false=0");
            props.Add("show_sql", "false");
            cfg.SetProperties(props);
            cfg.AddAssembly(typeof(Person).Assembly);
            connection = new SQLiteConnection(CONNECTION_STRING);
            connection.Open();

            // Get ourselves an NHibernate Session
            var sessions = cfg.BuildSessionFactory();
            sess = sessions.OpenSession();
        }

        private static void BuildSchema()
        {
            NHibernate.Tool.hbm2ddl.SchemaExport schemaExport
                = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
            schemaExport.Execute(false, true, false, connection, null);
        }

        public static void Insert()
        {
            // Create a Person...
            var person = new Person
            {
                Name = "Almudena",
                Surname = "Pamplinas",
                Age = 5
            };

            // And save it to the database
            sess.Save(person);
            sess.Flush();
        }

        public static void Retrieve()
        {
            IQuery q = sess.CreateQuery("FROM Person");
            foreach (var p in q.List().Cast<Person>())
            {
                Console.WriteLine(string.Format("{0} {1}, de {2} años.", 
                                                p.Name, p.Surname, p.Age));
            }
            Console.ReadLine();
        }
    }
}
0

1 Answer 1

7

Try using SchemaUpdate instead of SchemaExport. SchmaExport will drop all tables, constraints, etc and recreate them. SchemaUpdate will just bring your db up to date. However, I caution using SchemaUpdate/SchemaExport in a production environment as these are not production quality migration tools.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you, Vadim, that worked like a charm. Could you elaborate about your caution? These tests I'm doing are intented to learn for a desktop program I want to build using SQLite and NHibernate, and I need to automatically create SQLite databases from the schema. Is there a production-ready way to do it?
What I'm getting at, is I would not depend on my application/nhibernate to create the db and schema when it is deployed. I would create the db and schema manually and then deploy the application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.