Cannot Connect to LocalDB from .NET
You are trying something simple – just open a connection to a LocalDB instance from .NET but it is failing with a SqlException which has the following message:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
You know LocalDB is working, since you copied the connection string from within Visual Studio, but it just doesn’t work!
The cause of this issue is the connection string, however it may not be obvious at first glance:
var sqlConnection = new SqlConnection("Data Source=(localdb)\v11.0;Initial Catalog=Astronauts;Integrated Security=True;Connect Timeout=5");
The root cause is the Data Source and the \v in it – normally when you have a \ it complains unless it is a valid escape sequence like \r or \t and since it is not complaining here, it must be a valid escape sequence, just maybe one you are not familiar with, as \v is for a vertical tab.
The solution is easy when you realise that the escape sequence is messing with you, just add another slash:
var sqlConnection = new SqlConnection("Data Source=(localdb)\\v11.0;Initial Catalog=Astronauts;Integrated Security=True;Connect Timeout=5");
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)