jeudi 9 juillet 2015

Using NHibernate with SQLite

I've got a project set up using NHibernate and a MS SQL database for my masters project. However, my supervisor wants one using SQLite for demosntration purposes, meaning changes are required. I've found multiple pieces on using SQLite but cannot get them to work.

Steps taken:

  • Added the System.Data.SQLite DLL
  • Added an NHibernate Config file as follows

    NHibernate.Driver.SQLite20Driver Data Source=nhibernate.db;Version=3 NHibernate.Dialect.SQLiteDialect true=1;false=0 true

The problem is, my project uses a custom class called NHibernateProvider to create the database and calss mappings (not written by me, it is something we've used for multiple projects as a sort of black-box algorithm so far). The problem is it sets up a configuration using the .config file and maps based on that. The important sections for this are as follows:

/// <summary>
    /// The create configuration.
    /// </summary>
    private void CreateConfiguration()
    {
        this.Configuration = new Configuration();
        this.Configuration.DataBaseIntegration(
            c =>
            {
                c.Dialect<MsSql2008Dialect>();

                if (ConfigurationManager.ConnectionStrings["DefaultConnection"] == null
                    || ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString == null)
                {
                    throw new Exception();
                }

                c.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                c.SchemaAction = SchemaAutoAction.Validate;
            });

    }

Which is called nd then the configuration is used when we want to map all our database objects that inherit from a superclass called Entity:

/// <summary>
    /// The map model components.
    /// </summary>
    private void MapModelComponents()
    {
        var mapper = new ModelComponentModelMapper();

        this.CreateConfiguration();
        var di = new DirectoryInfo(AssemblyDirectory);
        var fis = di.GetFiles("*.dll");
        var list = new List<Type>();

        var loadedAssemblies =
            AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => x.GetName().ToString().StartsWith("LiSA_Service."))
                .ToList();
        var loadedAssemblyNames = new HashSet<string>();
        foreach (var loadedAssembly in loadedAssemblies)
        {
            loadedAssemblyNames.Add(loadedAssembly.GetName().Name + ".dll");
        }

        var assemblies = new List<Assembly>();
        foreach (var fileInfo in fis)
        {
            //if (!loadedAssemblyNames.Contains(fileInfo.ToString()))
            //{
                assemblies.Add(Assembly.LoadFile(fileInfo.FullName));
            //}
        }
        foreach (var asm in assemblies)
        {
            var mappings =
                asm.GetTypes().Where(
                    t => t.GetInterfaces().Any(i => i == typeof(IConformistHoldersProvider)));
            foreach (
            Type t in mappings)
            {
                try
                {
                    mapper.AddMapping(t);
                }
                catch (MappingException e)
                {
                    log.Error(e);
                }
            }
        }

        // Compile mappings
        var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
        this.Configuration.AddMapping(hbmMapping);

        try
        {
            var sv = new SchemaValidator(this.Configuration);
            sv.Validate();
            this.IsDbValid = true;
        }
        catch (Exception ex)
        {
            // Not ok
            this.IsDbValid = false;

            // Log
            this.log.Error(ex.Message, ex);
        }
    }

I've tried removing the confiuration-creation aprts, but this results in no configuration whatsoever, which obviously isn't what the aim, I simply want it to:

  • Use SQLite so we do not need a database server installed
  • (this should be automatic?)Save the .db in the program when closing the server component
  • Utilize the saved .db on startup so data is not lost (obviously)

If anyone can help me figure out what I'm missing, what the "secret sauce" is, so to speak, I would be extremely grateful!

If you are interested in the entire project, it is available at http://ift.tt/1Jpk71V in case this helps with further questions.

Aucun commentaire:

Enregistrer un commentaire