diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.cs index ec26b955e1..76399749a0 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.cs @@ -1068,7 +1068,7 @@ public override void Cancel() "SqlCommand.Cancel | API | Correlation | " + $"Object Id {ObjectID}, " + $"Activity Id {ActivityCorrelator.Current}, " + - $"Client Connection Id {_activeConnection.ClientConnectionId}, " + + $"Client Connection Id {_activeConnection?.ClientConnectionId}, " + $"Command Text '{CommandText}'"); SqlStatistics statistics = null; diff --git a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlCommandTest.cs b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlCommandTest.cs index 80ceba25af..59f35b4941 100644 --- a/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlCommandTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlCommandTest.cs @@ -562,6 +562,20 @@ public void ParameterCollectionTest() } } + /// + /// Verifies that SqlCommand.Cancel() is a no-op when Connection is null, + /// rather than throwing a NullReferenceException. Regression test for #4327. + /// + [Fact] + public void Cancel_WithNullConnection_DoesNotThrow() + { + using SqlCommand cmd = new SqlCommand(); + Assert.Null(cmd.Connection); + + // Should be a no-op, not throw NullReferenceException + cmd.Cancel(); + } + private static SqlConnection GetNonConnectingConnection() => new SqlConnection("Initial Catalog=a;Server=b;User ID=c;Password=d"); }