How can I create an in-memory Sqlite database with shared cache?
If I use the connectionstring mentioned in MS Docs for Sqlite In-Memory
Data Source=InMemorySample;Mode=Memory;Cache=Shared
Then I find that the in-memory database is not shared (I know this because the database creation script runs but tests report 'no such table' errors).
How do I make Sqlite in-memory shared cache work?
Reproduction
For me, this code throws "no such table" with either of the alleged in-memory connection strings, but works with a file-backed db.
void Main()
{
// Works fine with file-backed db.
if (File.Exists("temp.db")) File.Delete("temp.db");
CreateAndSelectAndWriteLine("Data Source=temp.db");
//Fails with either of the MS suggested datasource values
CreateAndSelectAndWriteLine("Data Source=:memory:");
CreateAndSelectAndWriteLine(
"Data Source=InMemorySample;Mode=Memory;Cache=Shared");
}
void CreateAndSelectAndWriteLine(string connectionString)
{
using var conn = new SqliteConnection(connectionString);
conn.Execute("Create Table HereIAm(id int)");
Console.WriteLine("------------------------------------------");
Console.WriteLine(connectionString);
try
{
Console.WriteLine(
conn.Query<int>("Select * from HereIAm")
.Count());
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("-----------------------------------------");
flows that create more than one instance of a DbContext can't succeed.that's a warning flag. A DbContext is a multi-entity Unit-of-Work, so what doesflowmean here? Why would there be more than one UoW per scenario/use-case/flow/domain? In any case, we can't guess what's wrong with code that isn't posted. As the docs sayThe database persists as long as at least one connection to it remains open. They don't say thatCache=Sharedwill keep connections open indefinitely.the in-memory database is not shared ... tests still report 'no such tablethat's not what "shared" means with SQLite. Normally, there can be only one connection per database, period. Shared means that multiple connections will be allowed, but even then, there can be only one writer. You need to keep a connectionMain, notCreateAndSelectAndWriteLine