Search code examples
sqlitenhibernatefluent-nhibernatenhibernate-configuration

When testing NHibernate with a SQLite In Memory configuration, how do you create another database?


We have an app that uses NHibernate/FluentNHibernate with a MsSqlConfiguration.MsSql2008.ConnectionString pointed at our SQL environment. The SQL servers have several database and we can connect to different databases by using a convention like so:

public class FactseDatabaseConvention : IClassConvention
{
    public void Apply(IClassInstance instance)
    {
        if (instance.EntityType.Namespace.EndsWith("Model.OtherEntities"))
        {
            instance.Schema("OtherDatabase.dbo");
        }
    }
}

This works and the correct queries are generated to access the OtherDatabase. The problem comes in when we want to test using a SQLiteConfiguration.Standard.InMemory() with our SessionFactory. The Persistence tests fail when SQLite is preparing:

System.Data.SQLite.SQLiteException : SQL logic error or missing database
unknown database OtherDatabase

This is the command it generates:

create table OtherDatabse.dbo_my_other_entity_table (
        Id UNIQUEIDENTIFIER not null,
        ... other properties
)

Is there a way I can change my SQLiteConfiguration to have it create 2 in-memory databases and, if so, how? Or should I just create a separate Session for testing these other entities?


Solution

  • I had this very same problem - (no longer since we moved from Sqlite to Sql Server LocalDB for tests).

    I do still have the code, what we did was provide a component which configures whether to use schemas or not, thus:

    public class SqlLiteMappingsHelper : IMappingsHelper
        {
            public string TextColumnTableSpecification
            {
                get
                {
                    // see sqlite faqs re: all varchars are very large whatever you specify
                    // http://www.sqlite.org/faq.html#q9
                    return "nvarchar(10)";
                }
            }
    
            public bool SchemasEnabled
            {
                get { return false; }
            }
        }
    

    (and one similar for sql server with SchemasEnabled = true) - in the web app you tell your IoC container to use the sql server one and in your test app you use the Sqlite one. Then in your convention:

    public void Apply(IClassInstance instance)
    {
        var helper = IoC.get<IMappingsHelper>();
        if (instance.EntityType.Namespace.EndsWith("Model.OtherEntities") && helper.SchemasEnabled)
        {
            instance.Schema("OtherDatabase.dbo");
        }
    }