Skip to content

Commit 1b4a3ac

Browse files
Improve DB connection and transaction cleanup logic
1 parent 77e7fda commit 1b4a3ac

File tree

4 files changed

+24
-5
lines changed

4 files changed

+24
-5
lines changed

Olive.Entities.Data.SqlServer/Olive.Entities.Data.SqlServer.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
33
<TargetFramework>netstandard2.0</TargetFramework>
4-
<Version>8.0.1</Version>
4+
<Version>8.0.2</Version>
55
</PropertyGroup>
66

77
<ItemGroup>

Olive.Entities.Data/Ado.Net/DataAccess.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,9 @@ public async Task<IDataReader> ExecuteReader(string command, CommandType command
179179
}
180180
catch (Exception ex)
181181
{
182+
// Close connection on error when not in a transaction
183+
CloseConnection(dbCommand.Connection);
184+
182185
throw new Exception("Error in running SQL Query.", ex).AddData("Command", command)
183186
.AddData("Parameters", @params?.Select(p => p.ParameterName + "=" + p.Value).ToString(" | "))
184187
.AddData("ConnectionString", dbCommand.Connection.ConnectionString);

Olive.Entities.Data/Ado.Net/DbTransactionScope.cs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,18 @@ async Task Setup(string connectionString)
9090
{
9191
var access = Context.Current.Database().GetAccess(connectionString);
9292
var connection = (DbConnection)await access.CreateConnection();
93-
var transaction = connection.BeginTransaction(IsolationLevel);
93+
94+
DbTransaction transaction;
95+
try
96+
{
97+
transaction = connection.BeginTransaction(IsolationLevel);
98+
}
99+
catch
100+
{
101+
connection.Close();
102+
connection.Dispose();
103+
throw;
104+
}
94105

95106
Connections.Add(connectionString, (connection, transaction));
96107
}
@@ -109,10 +120,15 @@ public void Dispose()
109120
// Root is not completed.
110121
IsAborted = true;
111122
Connections.Do(x => x.Value.Transaction.Rollback());
112-
Connections.Do(x => x.Value.Transaction.Dispose());
113123
}
114124

115-
Connections.Do(x => x.Value.Connection.Close());
125+
// Always dispose transactions and connections
126+
Connections.Do(x => x.Value.Transaction.Dispose());
127+
Connections.Do(x =>
128+
{
129+
x.Value.Connection.Close();
130+
x.Value.Connection.Dispose();
131+
});
116132
}
117133
else
118134
{

Olive.Entities.Data/Olive.Entities.Data.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
33
<TargetFramework>netstandard2.0</TargetFramework>
4-
<Version>8.0.3</Version>
4+
<Version>8.0.4</Version>
55
</PropertyGroup>
66

77
<ItemGroup>

0 commit comments

Comments
 (0)