Upgrade to 6.0: closing connection leaves SqlLite db file open
After upgrade to 6.0, previous functioning tests now fail. It appears the db file isn't getting closed properly. Here's an example:
[TestClass]
public class ChipProgrammingTests
{
private static readonly string testDbPath = @"c:\temp\_test";
/// <summary>
/// Create a local database to store a record of chip writes that have been performed on this machine
/// </summary>
public static void CreateDatabase(string databasePath)
{
string databaseDir = Path.GetDirectoryName(databasePath);
if (databaseDir is not null && !Directory.Exists(databaseDir))
Directory.CreateDirectory(databaseDir);
string commandText = @"
CREATE TABLE [MyDb](
[MyId] [nvarchar] (50) NOT NULL UNIQUE
);";
using var dbConnection = new SqliteConnection($"Data Source={databasePath}");
dbConnection.Open();
using var command = new SqliteCommand(commandText, dbConnection);
command.ExecuteNonQuery();
}
[TestMethod]
public void TestLocalDbCreation()
{
if (File.Exists(testDbPath))
File.Delete(testDbPath);
CreateDatabase(testDbPath);
File.Delete(testDbPath); // clean up
}
}
This test program gives the following error: System.IO.IOException HResult=0x80070020 Message=The process cannot access the file 'c:\temp_test' because it is being used by another process. Source=System.IO.FileSystem StackTrace: at System.IO.FileSystem.DeleteFile(String fullPath) at System.IO.File.Delete(String path) at Testing.Core.ChipProgramming.ChipProgrammingTests.TestLocalDbCreation() in
Microsoft.Data.Sqlite version: 6.0.0 Target framework: .NET 5.0 Operating system: Windows 11
This is by design, see breaking change note for 6.0.
The SQLite provider now pools connections, improving connection speed significantly but keeping connections open. You can disable pooling by adding Pooling=false to the connection string or calling SqliteConnection.ClearAllPools() at the point where you want them to be closed.
@roji Thanks. Looks like SqliteConnection.ClearAllPools() is exactly what I was looking for.
To take advantage of pooling, but yet ensure all connections are closed, is there an example of ensuring the pools are cleared and connection closed, when you are inheriting from the DBContext? Here is a snippet of SqliteDbContext from something that worked for me in EF Core 5.0 but now crashes under EF Core 6.0, even after Dispose() is called in the DbContext. It occurs when I follow it by trying to delete the sqlite file using File.Delete(fileInfo.FullName). The reason is the sqlite3-wal and sqlite3-shm (journal/intermediate) files still exist even after Dispose Context is completed. Though not required, I even tried adding: Database.GetDbConnection().Close(); in the dispose method and still does not work.
I use the following statement when I have to work with dbContext
using (_outputDb = new SqliteDbContext($"Data Source={fileInfo.FullName}")) {...}
the following is a snippet of the SqliteDbConext class
public class SqliteDbContext : DbContext<DbContextOptions<SqliteDbContext>>
{
private static DbContextOptions<SqliteDbContext> _builderOptions(string connectionString)
{
if (connectionString is null)
{
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, false)
.Build();
_connectionString = config.GetSection($"appSettings:sqliteDBConnectionString").Value;
}
else
{
_connectionString = connectionString;
}
var builder = new DbContextOptionsBuilder<SqliteDbContext>();
builder.UseSqlite(_connectionString);
return builder.Options;
}
public SqliteDbContext(string connectionString = null)
:base(_builderOptions(connectionString))
{
}
//And all the other properties....
public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#region IDisposable implementation
protected void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
Database.GetDbConnection().Close();
base.Dispose();
}
}
_disposed = true;
}
}
@TrevorFradsham have you seen the above suggestions to use ClearPool/ClearAllPools? That closes all pooled connections, and after that you should be able to delete your SQLite database file.
Doing Database.GetDbConnection().Close() has no effect on pooling, since Close simply returns the physical connection to the pool behind the scenes (that's the whole point of pooling). Regardless of pooling, it generally shouldn't be necessary to do this in your DbContext.Dispose, since EF Core automatically closes the DbConnection.
Yes I got your suggestion to work after. Thanks for the help. I had to include the using Microsoft.Data.Sqlite; before I could call the static method SqliteConnection.ClearAllPools();.
This code might help those reading this issue, add a this disposing to your DbContext
public override void Dispose()
{
if (Database.GetDbConnection() is SqliteConnection sqliteConnection)
{
SqliteConnection.ClearPool(sqliteConnection);
}
base.Dispose();
}