Microsoft.Data.SQLite: Reader is not correctly closed when an exception occurs on DbCommand.ExecuteScalar() with 3.0.0-preview8
When using Microsoft.Data.SQLite version 3.0.0-preview8.19405.11, when executing a command with ExecuteNonQuery, ExecuteScalar or ExecuteReader causes an exception, we cannot change the CommandText on the DbCommand any more.
Steps to reproduce
- Create a new .NET Core 3.0 console project on Windows using .NET Core SDK 3.0.100 - preview8.
- Add
<PackageReference Include="Microsoft.Data.SQLite" Version="3.0.0-preview8.19405.11" /> - Add the following code in
Program.cs:
using System.Data.Common;
using Microsoft.Data.Sqlite;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var conSb = new SqliteConnectionStringBuilder();
conSb.DataSource = ":memory:";
using (var con = new SqliteConnection(conSb.ConnectionString)) {
con.Open();
using (var cmd = con.CreateCommand()) {
cmd.CommandText = "SELECT 1 FROM NonExistent;";
try {
cmd.ExecuteScalar();
}
catch (DbException) {
}
cmd.CommandText = "SELECT 1;"; // fails
cmd.ExecuteScalar();
}
}
}
}
}
Expected behavior: Runs without exception.
Actual behavior:
Exception message: System.InvalidOperationException: 'An open reader is associated with this command. Close it before changing the CommandText property.'
Stack trace:
at Microsoft.Data.Sqlite.SqliteCommand.set_CommandText(String value)
at Test.Program.Main(String[] args) in C:\Users\developer4\Desktop\DebugMicrosoftSqlite\Program.cs:line 24
This problem doesn't occur when using version 2.2.6 of Microsoft.Data.SQLite.
Workaround: Close the DbCommand and create a new one for executing the next command.
Further technical details
EF Core version: 3.0.0-preview8.19405.11 Database Provider: Microsoft.Data.SQLite Operating system: Windows 10 Version 1903 x64 IDE: Visual Studio 2019 16.2.3
Thanks!
This is a by-design side effect of fixing #13830. (which had a few other subtle breaking changes like this)
I think #14044 will enable us to go back to the previous, more flexible behavior.
Oh wait, you called ExecuteScalar, so there shouldn't be an open data reader after the error. We should investigate.