SQLite unable to open database file or SQLite An attempt was made to load a program with an incorrect format

I had a SQLite database in an ASP.NET Web Forms project and it worked fine.  Recently I was using SQLite in an MVC5 project along with Ninject and I could not connect to the SQLite database.

After hours and stripping down the project to remove Ninject (which I thought was causing a conflict) it came down to two things.

1. Connection String for SQLite when coding Web Forms

In Web Forms I used the full path to the file.  If you try this in MVC you will get "sqlite unable to open database file"

HttpContext CTX = HttpContext.Current;
string DBFile = CTX.Server.MapPath(@"App_Data\TranslatorDB.sl3");

return Fluently.Configure()
 .Database(SQLiteConfiguration.Standard.UsingFile(_DBFile))
 .Mappings(m => m.FluentMappings.AddFromAssemblyOf<LangMap>())
 .BuildSessionFactory();


2. Connection String for SQLite when using MVC

With MVC You have to use a connection string vs. the path to the file. Why at this point I am not sure but I spent enough time on this already.

string connectionString = @"Data Source=|DataDirectory|\TranslatorDB.sl3";

return Fluently.Configure()
  .Database(SQLiteConfiguration.Standard.ConnectionString(connectionString))
 .Mappings(m => m.FluentMappings.AddFromAssemblyOf<LangMap>())
 .BuildSessionFactory();

3. An attempt was made to load a program with an incorrect format: The last issue I had when opening the SQLite database was "An attempt was made to load a program with an incorrect format."    I only hit this error when I was using Ninject.

I had to add a pre-build event in Visual Studio to use the x86 version of SQLite.

Copy “$(ProjectDir)bin\x86\SQLite.Interop.dll” “$(ProjectDir)$(OutDir)SQLite.Interop.dll”

ASP.NET SQLite / NHibernate C# Demo

This is a simple / scaled down project that can be useful as an overview of NHiberate with SQLite access and to provide a project to play around with data access.
The project is setup with:
  • Boostrap
  • NHibernate
  • SQLite Database under App_Data. It also contains the backup of the original database.
  • One Customer Entity Class
  • One Customer Mapping Class
  • One Data Access Class: NHibernate Connection, Session, Selects, Saves, and Deletes
  • It also contains a script to freeze the GridView header as found on ASPSnippets.
The customer data in this app was generated by using GenerateData.com.