Over a million developers have joined DZone.
Platinum Partner

Cannot Connect to LocalDB from .NET

· Database Zone

Speed up your development and test cycles with fully automated data delivery, view a 10 minute demo, brought to you in partnership with Delphix.

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.

image

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");

The Database Zone is brought to you in partnership with Delphix. Learn how you can easily virtualize and clone your database, read the white paper.

Topics:

Published at DZone with permission of Robert Maclean , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}