SQLite EF6 programmatically set connection string at runtime

后端 未结 3 566
情话喂你
情话喂你 2020-12-05 00:51

I try to migrate form EF 3.5 to 6 (with SQLite as database). We can not set the connection string in the app config file (this works without problems with ef6). We have to s

3条回答
  •  -上瘾入骨i
    2020-12-05 01:28

    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)
    {
    }
    

提交回复
热议问题