title: Membership.GetUser(), Unable to connect to connect to SQL Server Database
body: <p>I started using ASP.net MVC4, and I created a project with the Internet Application Template.</p>
  
  <p>I added some custom fields to the UserProfile default Model and Table, I also renamed it as "UserModel", and it's working just fine (login, register, etc.)</p>
  
  <p>I'm now trying to perform an SQL request to another entity, and therefore I need to get the ID of the current logged-in user. I found out I had to use <code>Membership.GetUser()</code> to access the current user, but I'm now completely stuck with this error : </p>
  
  <pre><code>     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)
  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.
  
  SQLExpress database file auto-creation error:
  
  Source Error:
  
  An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
  
  Stack Trace:
  
  
  [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)]
     System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5295167
     System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
     System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5307115
     System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145
     System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +920
     System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
     System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
     System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5309659
     System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
     System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection) +5311874
     System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
     System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +83
     System.Data.SqlClient.SqlConnection.Open() +96
     System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +76
  
  [HttpException (0x80004005): Unable to connect to SQL Server database.]
     System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +131
     System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89
     System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +27
     System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386
  
  
  Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929 
  </code></pre>
  
  <p>Here's my code:</p>
  
  <pre><code>namespace AppTest.Controllers
  {
      public class ThreadController : Controller
      {
          private DalContext db = new DalContext();
  
          public PartialViewResult OwnThreads()
          {
              MembershipUser currentUser = Membership.GetUser();
              int userGuid = (int) currentUser.ProviderUserKey;
              //List&lt;ThreadModel&gt; OwnThread = db.Threads.Where(t =&gt; t.Author.UserId == userGuid).ToList();
              return PartialView();
          }
  }
  </code></pre>
  
  <p>Here's my DataLayer :</p>
  
  <pre><code>namespace AppTest.DataAccessLayer
  {
      public class DalContext : DbContext
      {
          public DalContext()
              : base("DefaultConnection")
          {
          }
  
          public DbSet&lt;UserModel&gt; Users { get; set; }
  
          public DbSet&lt;CommentModel&gt; Comments { get; set; }
  
          public DbSet&lt;ThreadModel&gt; Threads { get; set; }
  
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
              modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;();
          }
  
      }
  }
  </code></pre>
  
  <p>Why is my call to <code>Membership.GetUser()</code> causing this error ? </p>
  
  <p>I don't even understand what the link is with the database, because other access to my database is working just fine. So I really don't understand.</p>
  
  <p>Thanks a lot for your help.</p>
  
  <hr>
  
  <p><strong>EDIT :</strong> Here's my web.config file, editing after the answer from user489998 </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=169433
    --&gt;
  &lt;configuration&gt;
    &lt;configSections&gt;
      &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt;
      &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt;
      &lt;sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core"&gt;
        &lt;section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /&gt;
        &lt;section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /&gt;
        &lt;section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" /&gt;
        &lt;section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" /&gt;
      &lt;/sectionGroup&gt;
    &lt;/configSections&gt;
    &lt;connectionStrings&gt;
      &lt;add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Soombu-20121217073143;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Soombu-20121217073143.mdf" providerName="System.Data.SqlClient" /&gt;
    &lt;/connectionStrings&gt;
    &lt;appSettings&gt;
      &lt;add key="webpages:Version" value="2.0.0.0" /&gt;
      &lt;add key="webpages:Enabled" value="false" /&gt;
      &lt;add key="PreserveLoginUrl" value="true" /&gt;
      &lt;add key="ClientValidationEnabled" value="true" /&gt;
      &lt;add key="UnobtrusiveJavaScriptEnabled" value="true" /&gt;
    &lt;/appSettings&gt;
    &lt;system.web&gt;
      &lt;membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15"&gt;
        &lt;providers&gt;
          &lt;clear /&gt;
          &lt;add name="SqlProvider" connectionStringName="DefaultConnection" applicationName="Soombu" type="System.Web.Security.SqlMembershipProvider" /&gt;
        &lt;/providers&gt;
      &lt;/membership&gt;
      &lt;compilation debug="true" targetFramework="4.5"&gt;
        &lt;assemblies&gt;
          &lt;add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /&gt;
        &lt;/assemblies&gt;
      &lt;/compilation&gt;
      &lt;httpRuntime targetFramework="4.5" /&gt;
      &lt;authentication mode="Forms"&gt;
        &lt;forms loginUrl="~/Account/Login" timeout="2880" /&gt;
      &lt;/authentication&gt;
      &lt;pages&gt;
        &lt;namespaces&gt;
          &lt;add namespace="System.Web.Helpers" /&gt;
          &lt;add namespace="System.Web.Mvc" /&gt;
          &lt;add namespace="System.Web.Mvc.Ajax" /&gt;
          &lt;add namespace="System.Web.Mvc.Html" /&gt;
          &lt;add namespace="System.Web.Optimization" /&gt;
          &lt;add namespace="System.Web.Routing" /&gt;
          &lt;add namespace="System.Web.WebPages" /&gt;
        &lt;/namespaces&gt;
      &lt;/pages&gt;
    &lt;/system.web&gt;
    &lt;system.webServer&gt;
      &lt;validation validateIntegratedModeConfiguration="false" /&gt;
      &lt;handlers&gt;
        &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /&gt;
        &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /&gt;
        &lt;remove name="ExtensionlessUrlHandler-Integrated-4.0" /&gt;
        &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /&gt;
        &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /&gt;
        &lt;add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt;
      &lt;/handlers&gt;
    &lt;/system.webServer&gt;
    &lt;runtime&gt;
      &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.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-2.0.0.0" newVersion="2.0.0.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" culture="neutral" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" /&gt;
        &lt;/dependentAssembly&gt;
        &lt;dependentAssembly&gt;
          &lt;assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" culture="neutral" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" /&gt;
        &lt;/dependentAssembly&gt;
      &lt;/assemblyBinding&gt;
      &lt;!-- This prevents the Windows Event Log from frequently logging that HMAC1 is being used (when the other party needs it). --&gt;
      &lt;legacyHMACWarning enabled="0" /&gt;
      &lt;!-- When targeting ASP.NET MVC 3, this assemblyBinding makes MVC 1 and 2 references relink
               to MVC 3 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it.
          &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt;
              &lt;dependentAssembly&gt;
                  &lt;assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /&gt;
                  &lt;bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /&gt;
              &lt;/dependentAssembly&gt;
          &lt;/assemblyBinding&gt;
           --&gt;
    &lt;/runtime&gt;
    &lt;entityFramework&gt;
      &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt;
        &lt;parameters&gt;
          &lt;parameter value="v11.0" /&gt;
        &lt;/parameters&gt;
      &lt;/defaultConnectionFactory&gt;
    &lt;/entityFramework&gt;
    &lt;system.net&gt;
      &lt;defaultProxy enabled="true" /&gt;
      &lt;settings&gt;
        &lt;!-- This setting causes .NET to check certificate revocation lists (CRL) 
                   before trusting HTTPS certificates.  But this setting tends to not 
                   be allowed in shared hosting environments. --&gt;
        &lt;!--&lt;servicePointManager checkCertificateRevocationList="true"/&gt;--&gt;
      &lt;/settings&gt;
    &lt;/system.net&gt;
    &lt;dotNetOpenAuth&gt;
      &lt;messaging&gt;
        &lt;untrustedWebRequest&gt;
          &lt;whitelistHosts&gt;
            &lt;!-- Uncomment to enable communication with localhost (should generally not activate in production!) --&gt;
            &lt;!--&lt;add name="localhost" /&gt;--&gt;
          &lt;/whitelistHosts&gt;
        &lt;/untrustedWebRequest&gt;
      &lt;/messaging&gt;
      &lt;!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --&gt;
      &lt;reporting enabled="true" /&gt;
      &lt;!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. --&gt;
      &lt;!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ --&gt;
      &lt;openid&gt;
        &lt;relyingParty&gt;
          &lt;security requireSsl="false"&gt;
            &lt;!-- Uncomment the trustedProviders tag if your relying party should only accept positive assertions from a closed set of OpenID Providers. --&gt;
            &lt;!--&lt;trustedProviders rejectAssertionsFromUntrustedProviders="true"&gt;
                          &lt;add endpoint="https://www.google.com/accounts/o8/ud" /&gt;
                      &lt;/trustedProviders&gt;--&gt;
          &lt;/security&gt;
          &lt;behaviors&gt;
            &lt;!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
                           with OPs that use Attribute Exchange (in various formats). --&gt;
            &lt;add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty" /&gt;
          &lt;/behaviors&gt;
        &lt;/relyingParty&gt;
      &lt;/openid&gt;
    &lt;/dotNetOpenAuth&gt;
    &lt;uri&gt;
      &lt;!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
               which is necessary for OpenID urls with unicode characters in the domain/host name.
               It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. --&gt;
      &lt;idn enabled="All" /&gt;
      &lt;iriParsing enabled="true" /&gt;
    &lt;/uri&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <p>I'm now getting this error: 
   Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'. </p>
  
  <p>I searched for this error, and all I found was something talking about aspnet_regsql.exe, which I don't even have on my PC.
  I'm using an embedded SQL server in Visual Studio 2012.
  I'm really lost right now.</p>