Jatin
Jatin

Reputation: 4063

Could not connect to SQL Server localdb instance

I have installed SQL Server 2014 localdb and SQL Server Management Studio. I am trying to connect to the localdb using a WPF application developed in Visual Studio.

Here is the connection string that I am using

<connectionStrings>
    <add name="ReservationContextString" 
         connectionString="Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ReservationDB;AttachDbFilename=|DataDirectory|\\ReservationDB.mdf" 
         providerName="System.Data.SqlClient" />
</connectionStrings>

When I run the application I get the following exception

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll but was not handled in user code

Additional information: 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

I am not sure why the application could not connect to localdb

Note: I am able to use the SQL Server Management Studio to connect to localdb using (localdb)\MSSQLLocalDB as Server Name. So, localdb seems to be installed properly.

Upvotes: 2

Views: 6162

Answers (2)

Korayem
Korayem

Reputation: 12497

In my case, I had to create the DB first from inside VS enter image description here

Then everything worked like a charm

Upvotes: 0

Jatin
Jatin

Reputation: 4063

Taking inspiration from this troubleshooting guide I was able to resolve the issue. The Entity Framework's defaultConnectionFactory should point to a localdb instance, but in app.config (or web.config), I had it set pointing to SQL Server Instance. It had to be changed to use localdb instance instead.

Old Entry

  <entityFramework>
      <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
      </defaultConnectionFactory>      
      ....
  </entityFramework>

should be (new code)

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
          <parameter value="MSSQLLocalDB" />
        </parameters>
      </defaultConnectionFactory>      
      ..      
  </entityFramework>

Notice the System.Data.Entity.Infrastructure.LocalDbConnectionFactory, instead of System.Data.Entity.Infrastructure.SqlConnectionFactory

Upvotes: 1

Related Questions