title: MVC4: UserIsInRole - Unable to connect to SQL Server database
body: <p>Breaking my head around with this, yesterday it worked fine and today it seems to be broken:</p>
  
  <p>This line is generating the error:</p>
  
  <pre><code>@if (Roles.IsUserInRole(HttpContext.Current.User.Identity.Name, "Admin"))
  </code></pre>
  
  <p>the error is:
  Unable to connect to SQL Server database.</p>
  
  <p>Whole exception:</p>
  
  <pre><code>System.Web.HttpException was unhandled by user code
    HResult=-2147467259
    Message=Unable to connect to SQL Server database.
    Source=System.Web
    ErrorCode=-2147467259
    WebEventCode=0
    StackTrace:
         at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
         at System.Web.DataAccess.SqlConnectionHelper.EnsureDBFile(String connectionString)
         at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation)
         at System.Web.Security.SqlRoleProvider.GetRolesForUser(String username)
         at WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username)
         at System.Web.Security.RolePrincipal.IsInRole(String role)
         at System.Web.Security.Roles.IsUserInRole(String username, String roleName)
         at ASP._Page_Views_Shared__LoginPartial_cshtml.Execute() in e:\LeasingWeb\LeasingWeb\Views\Shared\_LoginPartial.cshtml:line 10
         at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
         at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
         at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
         at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
         at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
         at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection)
         at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData)
         at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName)
         at ASP._Page_Views_Shared__Layout_cshtml.Execute() in e:\LeasingWeb\LeasingWeb\Views\Shared\_Layout.cshtml:line 35
         at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
         at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
         at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
         at System.Web.WebPages.WebPageBase.&lt;&gt;c__DisplayClass7.&lt;RenderPageCore&gt;b__6(TextWriter writer)
         at System.Web.WebPages.HelperResult.WriteTo(TextWriter writer)
         at System.Web.WebPages.WebPageBase.Write(HelperResult result)
         at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body)
         at System.Web.WebPages.WebPageBase.PopContext()
         at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
         at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
         at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
         at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
         at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
         at System.Web.Mvc.ControllerActionInvoker.&lt;&gt;c__DisplayClass1a.&lt;InvokeActionResultWithFilters&gt;b__17()
         at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
    InnerException: System.Web.HttpException
         HResult=-2147467259
         Message=Unable to connect to SQL Server database.
         Source=System.Web
         ErrorCode=-2147467259
         WebEventCode=0
         StackTrace:
              at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
              at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install)
              at System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString)
              at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
         InnerException: System.Data.SqlClient.SqlException
              HResult=-2146232060
              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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
              Source=.Net SqlClient Data Provider
              ErrorCode=-2146232060
              Class=20
              LineNumber=0
              Number=-1
              Server=""
              State=0
              StackTrace:
                   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
                   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
                   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
                   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
                   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
                   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions)
                   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
                   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
                   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection)
                   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
                   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
                   at System.Data.SqlClient.SqlConnection.Open()
                   at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
              InnerException: 
  </code></pre>
  
  <p>And as I said, this has been working fine for a few days, I have been using the default user DB that is created when making a new MVC4 project.</p>
  
  <p>Web.config:</p>
  
  <pre><code>&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;/configSections&gt;
    &lt;connectionStrings&gt;
      &lt;add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-LeasingWeb-20130113013313;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-LeasingWeb-20130113013313.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;compilation debug="true" targetFramework="4.5" /&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="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" /&gt;
          &lt;bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" /&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="v11.0" /&gt;
        &lt;/parameters&gt;
      &lt;/defaultConnectionFactory&gt;
    &lt;/entityFramework&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <p>Client 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)
  </code></pre>
  
  <p>The DB Tables seem fine, the users and roles exist and are just as before.</p>