Skip to content

SqlCommand.Cancel throws NullReferenceException when Connection is null #4327

@smophat7

Description

@smophat7

Describe the bug

After transitioning from v6.1.5 to v7.0.0, SqlCommand.Cancel now throws a NullReferenceException if SqlCommand.Connection is null.

Exception:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Data.SqlClient.SqlCommand.Cancel()
   at Program.<Main>$(String[] args) in /<path-to-project>/Program.cs:line 6

The line that causes the exception is a log statement near the beginning of the Cancel method. This PR included a change from Connection?.ClientConnectionId (source) to _activeConnection.ClientConnectionId (source), omitting the null-conditional operator, which was correctly retained in the Clone method's analogous log statement.

To reproduce

See this repo for a complete reproduction of the issue.

In summary, this following code behaves differently when using v7.0.0 compared to v6.1.5:

using Microsoft.Data.SqlClient;

SqlCommand command = new();
try
{
    command.Cancel();
    Console.WriteLine("Success!");
}
catch (Exception e)
{
    Console.WriteLine(e);
}

Expected behavior

Expected in v7.0.0: SqlCommand.Cancel() does not throw and is essentially a no-op
Actual in v7.0.0: SqlCommand.Cancel() throws a NullReferenceException.

Further technical details

Microsoft.Data.SqlClient version: v7.0.0
.NET target: .NET 10.0
SQL Server version: N/A
Operating system: Fedora Linux 44 (KDE Plasma Desktop Edition) - Linux version 7.0.6-200.fc44.x86_64

Additional context
The incorrect behavior is confirmed to still be present in v7.1.0-preview1.26124.5 (latest at time of writing).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Regression 💥Issues that are regressions introduced from earlier PRs.

    Type

    No fields configured for Bug.

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions