Skip to content

Commit

Permalink
Allow changing an open connection if it's not owned
Browse files Browse the repository at this point in the history
  • Loading branch information
Steven.Darby authored and Steven.Darby committed Apr 17, 2023
1 parent f53305f commit 0cf19b8
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/EFCore.Relational/Storage/RelationalConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ public virtual void SetDbConnection(DbConnection? value, bool contextOwnsConnect
{
if (!ReferenceEquals(_connection, value))
{
if (_openedCount > 0)
if (_connectionOwned && _openedCount > 0)
{
throw new InvalidOperationException(RelationalStrings.CannotChangeWhenOpen);
}
Expand Down
42 changes: 42 additions & 0 deletions test/EFCore.Relational.Tests/RelationalConnectionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,48 @@ public void Throws_when_rollback_is_called_without_active_transaction()
() => connection.RollbackTransaction()).Message);
}

[ConditionalFact]
public void Throws_when_changing_DbConnection_if_current_is_open_and_owned()
{
using var connection = new FakeRelationalConnection(
CreateOptions(new FakeRelationalOptionsExtension().WithConnectionString("Database=FrodoLives")));
Assert.Equal(0, connection.DbConnections.Count);

connection.Open();

Assert.Throws<InvalidOperationException>(() => connection.DbConnection = new FakeDbConnection("Fake"));
}

[ConditionalFact]
public void Disposes_when_changing_DbConnection_if_current_is_owned_and_not_open()
{
using var connection = new FakeRelationalConnection(
CreateOptions(new FakeRelationalOptionsExtension().WithConnectionString("Database=FrodoLives")));
Assert.Equal(0, connection.DbConnections.Count);

var dbConnection = connection.DbConnection;

Assert.Raises<EventArgs>(
h => dbConnection.Disposed += h.Invoke,
h => dbConnection.Disposed -= h.Invoke,
() => connection.DbConnection = new FakeDbConnection("Fake"));
}

[ConditionalFact]
public void Does_not_dispose_when_changing_DbConnection_if_current_is_open_and_not_owned()
{
using var connection = new FakeRelationalConnection();
Assert.Equal(0, connection.DbConnections.Count);

var dbConnection = new FakeDbConnection("Database=FrodoLives");
connection.DbConnection = dbConnection;
connection.Open();

connection.DbConnection = new FakeDbConnection("Database=FrodoLives");

Assert.Equal(ConnectionState.Open, dbConnection.State);
}

private static IDbContextOptions CreateOptions(params RelationalOptionsExtension[] optionsExtensions)
{
var optionsBuilder = new DbContextOptionsBuilder();
Expand Down

0 comments on commit 0cf19b8

Please sign in to comment.