SQLite & Entity Framework 6 "The underlying data provider failed to open"

c# entity-framework-6 sqlite winforms

Question

I see the following error when my Winforms application reaches the first Entity Framework data "request."

Message: The underlying provider failed to open.
InnerException: Data source cannot be empty.

To accommodate the user's needs, my connection string is being created dynamically.%appdata% route to a directory. I'm constructing it at launch time and updating theapp.config after it is constructed, using the connection string. The following code addresses this:

public void ConstructEntityFrameworkConnectionString(string dbFileName)
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    if (config.ConnectionStrings.ConnectionStrings["RemManagerDBEntities"] == null)
    {
        // Specify the provider name, server and database.
        var provider = "System.Data.SQLite.EF6";
        var providerName = "System.Data.EntityClient";
        var attacheddbfilename = dbFileName;

        // Initialize the connection string builder for the underlying provider.
        SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder {
                AttachDBFilename = attacheddbfilename,
                IntegratedSecurity = true,
                MultipleActiveResultSets = true,
                ConnectTimeout = 30,
                ApplicationName = "RemManagerDBEntities"
            };

        // Build the SqlConnection connection string.
        string providerString = sqlBuilder.ToString();

        // Initialize the EntityConnectionStringBuilder.
        EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder {
                Provider = provider,
                ProviderConnectionString = providerString,
                Metadata = @"res://*/EntityFramework.RemManagerDBModel.csdl|res://*/EntityFramework.RemManagerDBModel.ssdl|res://*/EntityFramework.RemManagerDBModel.msl"
            };

        var cs = new ConnectionStringSettings("RemManagerDBEntities", entityBuilder.ConnectionString, providerName);

        if (config.ConnectionStrings.ConnectionStrings["RemManagerDBEntities"] == null) 
        {
            config.ConnectionStrings.ConnectionStrings.Add(cs);
            config.Save(ConfigurationSaveMode.Modified);

            ConfigurationManager.RefreshSection("connectionStrings");
        }
    }
}

An example of a connection string it generates is:

metadata=res://*/EntityFramework.RemManagerDBModel.csdl|res://*/EntityFramework.RemManagerDBModel.ssdl|res://*/EntityFramework.RemManagerDBModel.msl; provider=System.Data.SQLite.EF6; provider connection string="AttachDbFilename=C:\Users\MacbookPro\AppData\Roaming\RemManager\Datasource\RemManagerDB.db; Integrated Security=True; MultipleActiveResultSets=True; Connect Timeout=30; Application Name=RemManagerDBEntities"

The program.cs file's main function includes a call to the method.

static void Main() 
{
    var conController = new ConnectionController();
    conController.ConstructEntityFrameworkConnectionString($"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\RemManager\\Datasource\\RemManagerDB.db");

    // Start the application
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new RemManager());
}

I've installed the following NuGet packages:

  • Instance Model 6
  • System.Data.SQLite
  • System.Data.SQLite.EF6
  • System.Data.SQLite.Core
  • System.Data.SQLite.Linq

My first setup instructions were based on the website listed below, with the second link's modification.

https://www.codeproject.com/Tips/1056400/Setting-up-SQLite-and-Entity-Framework-Code-First

https://github.com/ErikEJ/SqlCeToolbox/wiki/EF6-workflow-with-SQLite-DDEX-provider

Here is an example of a request I made to the database using the entity framework. Stepping through the code reveals that the exception starts at thedb.tblGroups.Select line.

public class GroupController : IGroup
{
    public List<tblGroup> SelectAllGroups()
    {
        using (var db = new RemManagerDBEntities())
        {
            return db.tblGroups.Select(g => g).ToList();
        }
    }

  ...

}

The app.config is the last component of the puzzle. The following configuration is current.

<?xml version="1.0" encoding="utf-8"?>
 <configuration>
  <configSections>
   <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <!-- See Datasource.ConnectionController for the connection string builder.-->
  </connectionStrings>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>
  </entityFramework>
  <appSettings>
    <add key="databaseFilePath" value="" />
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
       <system.web>
         <membership defaultProvider="ClientAuthenticationMembershipProvider">
           <providers>
             <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
           </providers>
         </roleManager>
       </system.web>
       <system.data>
         <DbProviderFactories>
           <remove invariant="System.Data.SQLite.EF6" />
           <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
    </DbProviderFactories>
  </system.data>
</configuration>

For what it's worth, entity framework is configured to operate from a database first. Additionally, I'm using SQLite 1.0.106.0 and Entity Framework 6.2.

I've done my best to search other websites for a workable solution that takes into account the fact that I'm merging Entity Framework with SQLite, but I haven't had much luck. I've had trouble coming up with many solutions, even when I remove SQLite out of the picture. Zzz-97-Zzz was one of the finest questions I had come across, although I already follow the advice given in the proposed solution.

Earlier, I ran across a similar issue, except it included localdb. The programme was previously operating on the local database, but since I've been trying to make it more self-contained and user-friendly, this problem has begun (e.g. not needing to modify the exe.config manually once installed).

Any recommendations would be much appreciated.

1
0
1/20/2018 12:59:19 PM

Accepted Answer

SqlConnectionStringBuilder cannot be used with SQLite; instead, use SQLiteConnectionStringBuilder and change the DataSource attribute to the name of the database file.

0
1/20/2018 11:49:52 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow