When I create a password protected SQLite database like here ,EnsureCreated();
throws an object disposed exception:
I have no idea why. Added NuGet packages :
Microsoft.EntityFrameworkCore.Sqlite v1.1.0
System.Data.SQLite.Core v1.0.104
DbContext
class:
using Microsoft.EntityFrameworkCore;
using System.Data.SQLite;
class TestMenuDataContext : DbContext
{
public SQLiteConnection Connection { get; set; }
public SQLiteCommand Command { get; set; }
public TestMenuDataContext()
{
//Database.Migrate();
//Database.EnsureCreated();
}
public DbSet<Test> TestMenu { get; set; }
... and some more other tables ...
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
Connection = new SQLiteConnection(@"Data Source=TestMenu.db;");
Connection.Open();
Command = Connection.CreateCommand();
Command.CommandText = "SELECT quote($password);";
Command.Parameters.AddWithValue("$password", "TheUltimatePasswordPhraseWillBeAddedLaterHere");
var escapedPassword = (string)Command.ExecuteScalar();
Command.Parameters.Clear();
Command.CommandText = "PRAGMA key = " + escapedPassword + ";";
Command.ExecuteNonQuery();
optionsBuilder.UseSqlite(Connection);
// instead of password configuration above with this single line (no pw) below everything is fine
//optionsBuilder.UseSqlite("Filename=./TestMenu.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
... some key constraints
}
}
The calling part in the WPF Gui (no MVVM):
private TestMenuDataContext _Db;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//Do not load your data at design time.
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
_Db = new TestMenuDataContext();
_Db.Database.EnsureCreated();
Before that I had local context objects, local connection and command objects:
using (var db = new TestMenuDataContext())
{
db.Database.EnsureCreated();
And :
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var conn = new SQLiteConnection(@"Data Source=yourSQLite.db;");
conn.Open();
var command = conn.CreateCommand();
command.CommandText = "PRAGMA key = password;";
command.ExecuteNonQuery();
optionsBuilder.UseSqlite(conn);
Additionally tested as proposed :
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
using (SQLiteConnection connection = new SQLiteConnection(@"Data Source=TestMenu.db;"))
using (SQLiteCommand command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "SELECT quote($password);";
command.Parameters.AddWithValue("$password", "TheUltimatePasswordPhraseWillBeAddedHere");
var escapedPassword = (string)command.ExecuteScalar();
command.Parameters.Clear();
command.CommandText = "PRAGMA key = " + escapedPassword + ";";
command.ExecuteNonQuery();
optionsBuilder.UseSqlite(connection);
}