I need to use sqllite in-memory database while the app is running, right now it closes the connection after each call and the database is lost. This is useful for testing, but not so useful when one needs to have persistent sqllite in-memory database.
If I use in-memory connection string for SQLLite:
``` C#
options.UseSqlite("Data Source=:memory:");
Then my init code fails:
``` C#
public class InitDatabase: IInitDatabase {
private readonly ApplicationDbContext db;
public InitDatabase(ApplicationDbContext _db) {
db = _db;
}
public void Init() {
db.Database.EnsureCreated();
db.Add(new ApplicationUser {
Email = "[email protected]",
UserName = "test"
});
db.SaveChanges();
}
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) {
// ...
app.ApplicationServices.GetService<IInitDatabase>().Init();
}
According to other issue #4922 it closes the connection to database after EnsureCreated and then the memory is empty again.
My code works correctly with filebased SQLLite like this:
C#
options.UseSqlite("Data Source=some.db");
Looks like a dupe of #4922
@ajcvickers sorry about that, thing is searching "sqllite memory" gives no open issues or closed ones! Weird fulltext search.
I reopen this, since what I want is a bit different: to persist in-memory database while app is running.
Edit If this is implemented, it could be useful to think about how to make it work also with shared in-memory SqlLite databases. E.g. connection string: FullUri=file::memory:?cache=shared
does not work with this currently at all, complains that FullUri is not suported, it has worked with System.Data.SQLite
in the past.
Found a solution to persistent in-memory SQLLite database, it was simple after all:
``` c#
public class Startup
{
private SqliteConnection inMemorySqlite;
public void ConfigureServices(IServiceCollection services)
{
inMemorySqlite = new SqliteConnection("Data Source=:memory:");
inMemorySqlite.Open();
// ...
services.AddDbContext<ApplicationDbContext>(options => {
options.UseSqlite(inMemorySqlite);
});
}
}
```
Turns out the UseSqllite takes in DbConnection, and this meant I can just store it in the startup so it remains open.
_sqliteConnection.Open();
is needed when data-source is "in-memory".
Most helpful comment
Found a solution to persistent in-memory SQLLite database, it was simple after all:
``` c#
public class Startup
{
private SqliteConnection inMemorySqlite;
}
```
Turns out the UseSqllite takes in DbConnection, and this meant I can just store it in the startup so it remains open.