Skip to content

Commit 0cf19b8

Browse files
Steven.DarbySteven.Darby
Steven.Darby
authored and
Steven.Darby
committed
Allow changing an open connection if it's not owned
Fixes dotnet#30704
1 parent f53305f commit 0cf19b8

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/EFCore.Relational/Storage/RelationalConnection.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ public virtual void SetDbConnection(DbConnection? value, bool contextOwnsConnect
181181
{
182182
if (!ReferenceEquals(_connection, value))
183183
{
184-
if (_openedCount > 0)
184+
if (_connectionOwned && _openedCount > 0)
185185
{
186186
throw new InvalidOperationException(RelationalStrings.CannotChangeWhenOpen);
187187
}

test/EFCore.Relational.Tests/RelationalConnectionTest.cs

+42
Original file line numberDiff line numberDiff line change
@@ -1012,6 +1012,48 @@ public void Throws_when_rollback_is_called_without_active_transaction()
10121012
() => connection.RollbackTransaction()).Message);
10131013
}
10141014

1015+
[ConditionalFact]
1016+
public void Throws_when_changing_DbConnection_if_current_is_open_and_owned()
1017+
{
1018+
using var connection = new FakeRelationalConnection(
1019+
CreateOptions(new FakeRelationalOptionsExtension().WithConnectionString("Database=FrodoLives")));
1020+
Assert.Equal(0, connection.DbConnections.Count);
1021+
1022+
connection.Open();
1023+
1024+
Assert.Throws<InvalidOperationException>(() => connection.DbConnection = new FakeDbConnection("Fake"));
1025+
}
1026+
1027+
[ConditionalFact]
1028+
public void Disposes_when_changing_DbConnection_if_current_is_owned_and_not_open()
1029+
{
1030+
using var connection = new FakeRelationalConnection(
1031+
CreateOptions(new FakeRelationalOptionsExtension().WithConnectionString("Database=FrodoLives")));
1032+
Assert.Equal(0, connection.DbConnections.Count);
1033+
1034+
var dbConnection = connection.DbConnection;
1035+
1036+
Assert.Raises<EventArgs>(
1037+
h => dbConnection.Disposed += h.Invoke,
1038+
h => dbConnection.Disposed -= h.Invoke,
1039+
() => connection.DbConnection = new FakeDbConnection("Fake"));
1040+
}
1041+
1042+
[ConditionalFact]
1043+
public void Does_not_dispose_when_changing_DbConnection_if_current_is_open_and_not_owned()
1044+
{
1045+
using var connection = new FakeRelationalConnection();
1046+
Assert.Equal(0, connection.DbConnections.Count);
1047+
1048+
var dbConnection = new FakeDbConnection("Database=FrodoLives");
1049+
connection.DbConnection = dbConnection;
1050+
connection.Open();
1051+
1052+
connection.DbConnection = new FakeDbConnection("Database=FrodoLives");
1053+
1054+
Assert.Equal(ConnectionState.Open, dbConnection.State);
1055+
}
1056+
10151057
private static IDbContextOptions CreateOptions(params RelationalOptionsExtension[] optionsExtensions)
10161058
{
10171059
var optionsBuilder = new DbContextOptionsBuilder();

0 commit comments

Comments
 (0)