title: Sometimes getting "A network-related or instance-specific error occurred while establishing a connection to SQL Server."
body: <p>Every now and then I am getting </p>
  
  <blockquote>
    <p>A network-related or instance-specific error occurred while establishing a connection to SQL Server.</p>
  </blockquote>
  
  <p>and in the details it says</p>
  
  <blockquote>
    <p>SQL Server Express database file auto-creation error</p>
  </blockquote>
  
  <p>This error appears randomly. Sometimes when I go to another page it loads fine and when I get back to the <code>/Home/Index</code> the error disappears.</p>
  
  <p>I am using Asp.Net MVC 5 and on localhost.</p>
  
  <p>I have only one <code>DefaultConnection</code> in <code>web.config</code>:</p>
  
  <pre><code>&lt;connectionStrings&gt;
      &lt;!--&lt;clear /&gt;--&gt;
      &lt;add name="DefaultConnection" 
           connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\RadiologyManager.mdf;Initial Catalog=RadiologyManager;Integrated Security=True" 
           providerName="System.Data.SqlClient" /&gt;
  &lt;/connectionStrings&gt;
  </code></pre>
  
  <p>I tried adding clear, as mentioned <a href="https://stackoverflow.com/questions/19346938/a-network-releated-or-instance-specific-error-occurred-while-establishing-a-conn">here</a>, but it gives another error that a connection from <code>machine.config</code> is not found.</p>
  
  <p><strong>Error</strong></p>
  
  <blockquote>
    <p>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)</p>
    
    <p>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p>
    
    <p>SQL Server Express database file auto-creation error:</p>
    
    <p>The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:</p>
    
    <p>If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: <a href="http://go.microsoft.com/fwlink/?LinkId=160102" rel="nofollow">http://go.microsoft.com/fwlink/?LinkId=160102</a>. If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist.</p>
    
    <p>If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database.</p>
    
    <p>Sql Server Express must be installed on the machine.</p>
    
    <p>The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.</p>
  </blockquote>
  
  <p><strong>Stack Trace</strong></p>
  
  <blockquote>
    <p>[SqlException (0x80131904): 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)]</p>
    
    <p>System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5341687  </p>
    
    <p>System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +546<br>
    System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5353471<br>
    System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145<br>
    System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +923<br>
    System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +311<br>
    System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +646<br>
    System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5356769<br>
    System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38<br>
    System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource<code>1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&amp; connection) +5358970<br>
    System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource</code>1 retry, DbConnectionOptions userOptions) +146<br>
    System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<code>1 retry, DbConnectionOptions userOptions) +16<br>
    System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource</code>1 retry) +94<br>
    System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110<br>
    System.Data.SqlClient.SqlConnection.Open() +96<br>
    System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +75  </p>
    
    <p>[HttpException (0x80004005): Unable to connect to SQL Server database.]<br>
    System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +130<br>
    System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89<br>
    System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +27<br>
    System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386  </p>
  </blockquote>
  
  <p><em>~Edit~</em><br>
  <strong>Web.Config</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;!--
    For more information on how to configure your ASP.NET application, please visit
    http://go.microsoft.com/fwlink/?LinkId=301880
    --&gt;
  &lt;configuration&gt;
    &lt;configSections&gt;
  
      &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt;
    &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt;&lt;/configSections&gt;
    &lt;connectionStrings&gt;
      &lt;!--&lt;clear /&gt;--&gt;
      &lt;add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=RadiologyManager;Integrated Security=True" providerName="System.Data.SqlClient" /&gt;
    &lt;/connectionStrings&gt;
    &lt;appSettings&gt;
      &lt;add key="webpages:Version" value="3.0.0.0" /&gt;
      &lt;add key="webpages:Enabled" value="false" /&gt;
      &lt;add key="ClientValidationEnabled" value="true" /&gt;
      &lt;add key="UnobtrusiveJavaScriptEnabled" value="true" /&gt;
    &lt;/appSettings&gt;
    &lt;system.web&gt;
      &lt;authentication mode="None" /&gt;
      &lt;roleManager enabled="true" /&gt;
      &lt;compilation debug="true" targetFramework="4.5" /&gt;
      &lt;httpRuntime targetFramework="4.5" /&gt;
    &lt;/system.web&gt;
    &lt;system.webServer&gt;
      &lt;modules&gt;
        &lt;remove name="FormsAuthentication" /&gt;
      &lt;/modules&gt;
    &lt;/system.webServer&gt;
    &lt;runtime&gt;
      &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" /&gt;
        &lt;/dependentAssembly&gt;
      &lt;/assemblyBinding&gt;
    &lt;/runtime&gt;
    &lt;entityFramework&gt;
      &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt;
        &lt;parameters&gt;
          &lt;parameter value="mssqllocaldb" /&gt;
        &lt;/parameters&gt;
      &lt;/defaultConnectionFactory&gt;
      &lt;providers&gt;
        &lt;provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /&gt;
      &lt;/providers&gt;
    &lt;/entityFramework&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <hr>
  
  <h2>Update (Solved)</h2>
  
  <p>As suggested by <a href="https://stackoverflow.com/users/61305/aaron-bertrand">Aaron Bertrand</a> I installed SQL Server Express 2014 with Management Studio. </p>
  
  <p>SQL Server 2008 and 2012 kept failing to install during setup. After two days of struggle I managed to install 2012 but it failed to load. So I went with SQL Server Express 2014 with Management Studio and it installed without any problem and working fine. So far so good.</p>
  
  <p>Update the connection in <code>web.config</code> as following</p>
  
  <pre><code>&lt;connectionStrings&gt;
      &lt;add name="DefaultConnection" connectionString="Data Source=MYSYS\SQLEXPRESS;Initial Catalog=RadiologyData;User ID=sa;Pooling=False;Password=abc123" providerName="System.Data.SqlClient" /&gt;
  &lt;/connectionStrings&gt;
  </code></pre>
  
  <p>and</p>
  
  <pre><code>&lt;entityFramework&gt;
      &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"&gt;
      &lt;!--&lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt;--&gt;
        &lt;parameters&gt;
          &lt;parameter value="Data Source=MYSYS\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" /&gt;
          &lt;!--&lt;parameter value="mssqllocaldb" /&gt;--&gt;
        &lt;/parameters&gt;
      &lt;/defaultConnectionFactory&gt;
      &lt;providers&gt;
        &lt;provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /&gt;
      &lt;/providers&gt;
    &lt;/entityFramework&gt;
  &lt;/configuration&gt;
  </code></pre>