dotnet / dotnet/SqlClient

SqlConnection doesn't restore database in the new session if connection is lost

Open
#4,108 6 comments 0 reactions 2 assignees Claimed by @apoorvdeshmukh View on GitHub
Dominant language
C#
Stars
989
Forks
340
Avg merge
4d 18h
Merged PRs (30d)
69

Description

### Describe the bug
this issue doesn't happen all the time but if one connection (on master db) is used to run multiple queries and one of the queries is "Use [db name]", sometimes the query after this is executed in the master database

### To reproduce
1- Open SqlConnecion passing master db connection string
2- Create a command from the connection and set the command text from the list below, one by one and run command.ExecuteNonQuery()
CREATE DATABASE [$(DatabaseName)]

USE [$(DatabaseName)]

CREATE Table tb1 (c1 int)

3. I'm not sure what is causing the connection session to be lost, but what happens is, sometimes we see the application role created in the master database.

### Expected behavior
queries after "Use [db name]" should always executed in the db not master even if the connection is on the master database

### Further technical details
Microsoft.Data.SqlClient version: (6.1.3)
.NET target: .NET Framework 4.7.2 and .NET 8.0
SQL Server version: (e.g. SQL Server 2022)
Operating system: Windows Server 2022

**Additional context**
Add any other context about the problem here.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.