Skip to content

Commit a17f5ea

Browse files
[7.0.2 Cherry-pick] Fix SqlCommand.Cancell null ref exception (#4373)
Co-authored-by: Malcolm Daigle <mdaigle@microsoft.com>
1 parent 221fac8 commit a17f5ea

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlCommand.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1068,7 +1068,7 @@ public override void Cancel()
10681068
"SqlCommand.Cancel | API | Correlation | " +
10691069
$"Object Id {ObjectID}, " +
10701070
$"Activity Id {ActivityCorrelator.Current}, " +
1071-
$"Client Connection Id {_activeConnection.ClientConnectionId}, " +
1071+
$"Client Connection Id {_activeConnection?.ClientConnectionId}, " +
10721072
$"Command Text '{CommandText}'");
10731073

10741074
SqlStatistics statistics = null;

src/Microsoft.Data.SqlClient/tests/FunctionalTests/SqlCommandTest.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,20 @@ public void ParameterCollectionTest()
562562
}
563563
}
564564

565+
/// <summary>
566+
/// Verifies that SqlCommand.Cancel() is a no-op when Connection is null,
567+
/// rather than throwing a NullReferenceException. Regression test for #4327.
568+
/// </summary>
569+
[Fact]
570+
public void Cancel_WithNullConnection_DoesNotThrow()
571+
{
572+
using SqlCommand cmd = new SqlCommand();
573+
Assert.Null(cmd.Connection);
574+
575+
// Should be a no-op, not throw NullReferenceException
576+
cmd.Cancel();
577+
}
578+
565579
private static SqlConnection GetNonConnectingConnection() =>
566580
new SqlConnection("Initial Catalog=a;Server=b;User ID=c;Password=d");
567581
}

0 commit comments

Comments
 (0)