I do something like:
public class MyDbContext : DbContext {
public MyDbContext(bool readOnlyFlag) {
// Monitor.Enter(theLock); // needed ??
this.readOnlyFlag = readOnlyFlag;
// Database.EnsureCreated(); // needed ??
}
public DbSet<MyData> MyData { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
string connectionString = "Data Source=C:\\mydb.db;";
if (readOnlyFlag) connectionString += "Mode=ReadOnly;";
optionsBuilder.UseSqlite(connectionString);
}
public override void Dispose() {
// Database.CloseConnection(); // needed ??
base.Dispose();
// Monitor.Exit(theLock); // needed ??
}
readonly bool readOnlyFlag;
// readonly object theLock = new object(); // needed ??
}
and then:
using (var dbc = new MyDbContext(true)) {
dbc.MyData.Where( ... code
}
I call such code this from multiple concurrent threads to run different queries.. (in a .Net Core 3.0 console App)
Questions:
If I understand correctly the database file will be opened when the
using
block starts and closed when it ends. Closing and opening a file on each query seems really inefficient but I could not find any reference to whether or not it's OK to keep a singletonMyDbContext
(ie in theProgram
class) and reuse it ?If I can reuse
MyDbContext
should I then use a lock around queries ?In general do I need to use ie the
Monitor
remarked above to make sure queries don't run concurrently ? I've seen posts saying Sqlite needs this ?Do I need to call
Database.CloseConnection()
? seems to work fine without it but I've seen posts where it was called like above remarked ?is Database.EnsureCreated() needed for Sqlite ?
Thanks!