SQLite EF6 programmatically set connection string at runtime

女生的网名这么多〃 提交于 2019-11-27 19:05:01

I was having the same problem. I found a workaround by using a different constructor from the base DbContext class:

public DbContext(DbConnection existingConnection, bool contextOwnsConnection);

Using this override you can pass an SQLiteConnection instead which you set the connection string on. So for example you can add a new constructor to your FirmwareContext.

public FirmwareContext(string connectionString)
    : base(new SQLiteConnection() { ConnectionString = connectionString }, true)
{
}

Or even

public FirmwareContext(string filename)
    : base(new SQLiteConnection() { ConnectionString =
            new SQLiteConnectionStringBuilder()
                { DataSource = filename, ForeignKeys = true }
            .ConnectionString }, true)
{
}

After looking at this further it seems the problem is that there isn't a IDbConnectionFactory defined for SQLite. So another approach would be to define your own factory implementation.

public class SQLiteConnectionFactory : IDbConnectionFactory
{
    public DbConnection CreateConnection(string connectionString)
    {
        return new SQLiteConnection(connectionString);
    }
}

Then replace the defaultConnectionFactory entry in your 'app.config' with something like:

<defaultConnectionFactory type="MyDAL.SQLiteConnectionFactory, MyDAL" />

Normally the connection string in config would look like this

<add name="MuthootOneClientEntities" connectionString="metadata=res://*/LocalData.MuthootClientContext.csdl|res://*/LocalData.MuthootClientContext.ssdl|res://*/LocalData.MuthootClientContext.msl;provider=System.Data.SQLite;provider connection string=&quot;data source=D:\LocalRepo\trunk\dev\Muthoot.MuthootOne.API\src\Muthoot.MuthootOne.API.Services\LocalData\FD1CBA65-1B68-449F-8E6D-A652137466D4.db&quot;" providerName="System.Data.EntityClient" />

change the above to following.(remove &quot ; to "") and mention it directly in entity context connection string with your own database location.

public partial class MuthootClientEntities : DbContext
{
    public MuthootClientEntities()
        : base(@"metadata=res://*/LocalData.MuthootClientContext.csdl|res://*/LocalData.MuthootClientContext.ssdl|res://*/LocalData.MuthootClientContext.msl;provider=System.Data.SQLite;provider connection string=""data source=" + System.Environment.CurrentDirectory + @"\LocalData\FD1CBA65-1B68-449F-8E6D-A652137466D4.db""")        
    {
        var test = System.Environment.CurrentDirectory;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!