title: How to implement ASP.NET identity: CREATE DATABASE permission denied in database 'master'
body: <p>First of all, I already checked here:
  <a href="https://stackoverflow.com/questions/18297052/asp-net-identity-how-to-set-target-db">ASP.Net Identity how to set target DB?</a></p>
  
  <p>I'm now getting this error</p>
  
  <blockquote>
    <p>CREATE DATABASE permission denied in database 'master'.</p>
  </blockquote>
  
  <p>On this line of code:</p>
  
  <pre><code>Dim user As User = manager.Find(Trim(Username.Text), Trim(Password.Text))
  </code></pre>
  
  <p>Full error:</p>
  
  <blockquote>
    <p>[SqlException (0x80131904): CREATE DATABASE permission denied in database 'master'.]<br>
    System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action<code>1 wrapCloseInAction) +3249852<br>
    System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +345<br>
    System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean&amp; dataReady) +4927<br>
    System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +1287<br>
    System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource</code>1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +367<br>
    System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +386<br>
    System.Data.Entity.Infrastructure.Interception.InternalDispatcher<code>1.Dispatch(TTarget target, Func</code>3 operation, TInterceptionContext interceptionContext, Action<code>3 executing, Action</code>3 executed) +965<br>
    System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) +505<br>
    System.Data.Entity.SqlServer.&lt;>c__DisplayClass1a.b__19(DbConnection conn) +136<br>
    System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action<code>1 act) +347<br>
    System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action</code>1 act) +916<br>
    System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable<code>1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +117<br>
    System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable</code>1 commandTimeout, StoreItemCollection storeItemCollection) +212<br>
    System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +172<br>
    System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +175<br>
    System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +116<br>
    System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func<code>3 createMigrator, ObjectContext objectContext) +121<br>
    System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +169<br>
    System.Data.Entity.CreateDatabaseIfNotExists</code>1.InitializeDatabase(TContext context) +257<br>
    System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action  action) +72<br>
    System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +483<br>
    System.Data.Entity.Internal.RetryAction<code>1.PerformAction(TInput input) +177<br>
    System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action</code>1 action) +274<br>
    System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +37<br>
    System.Data.Entity.Internal.Linq.InternalSet<code>1.Initialize() +76<br>
    System.Data.Entity.Internal.Linq.InternalSet</code>1.get_InternalContext() +21<br>
    System.Data.Entity.Infrastructure.DbQuery<code>1.System.Linq.IQueryable.get_Provider() +59<br>
    System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable</code>1 source, Expression<code>1 predicate, CancellationToken cancellationToken) +208<br>
    System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable</code>1 source, Expression`1 predicate) +172  </p>
    
    <p>Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext() +502<br>
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13855856<br>
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61<br>
    Microsoft.AspNet.Identity.CultureAwaiter<code>1.GetResult() +48<br>
    Microsoft.AspNet.Identity.&lt;FindAsync&gt;d__12.MoveNext() +357<br>
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13855856<br>
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61<br>
    Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func</code>1 func) +348<br>
    MyApp.Login_identity.UserLogin_Click(Object sender, EventArgs e) in C:\MyApp\Login_identity.aspx.vb:168<br>
    System.Web.UI.WebControls.Button.OnClick(EventArgs e) +11747645<br>
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +150<br>
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3360  </p>
  </blockquote>
  
  <p>I changed the <code>DbContext</code> initialization in <code>AppModel.vb</code> to my existing connection string <code>conn1</code>, which points to the SQL Server database I already converted to the new identity tables.</p>
  
  <p>My connection string: </p>
  
  <pre><code>&lt;add name="conn1" 
       connectionString="data source=(local)\sqlexpress;Initial Catalog=myapp;User Id=sa;Password=XXXX;" 
       providerName="System.Data.SqlClient" /&gt;
  </code></pre>
  
  <p><code>AppModel.vb</code>:</p>
  
  <pre><code>Imports Microsoft.AspNet.Identity
  Imports Microsoft.AspNet.Identity.EntityFramework
  Imports System.Collections.Generic
  Imports System.ComponentModel.DataAnnotations
  Imports System.Data.Entity
  Imports System.Linq
  Imports System.Web
  
  Namespace AspnetIdentitySample.Models
      Public Class ApplicationUser
          Inherits IdentityUser
          ' HomeTown will be stored in the same table as Users
          Public Property HomeTown() As String
              Get
                  Return m_HomeTown
              End Get
              Set(value As String)
                  m_HomeTown = Value
              End Set
          End Property
          Private m_HomeTown As String
          Public Overridable Property ToDoes() As ICollection(Of ToDo)
              Get
                  Return m_ToDoes
              End Get
              Set(value As ICollection(Of ToDo))
                  m_ToDoes = Value
              End Set
          End Property
          Private m_ToDoes As ICollection(Of ToDo) 
  
          ' FirstName &amp; LastName will be stored in a different table called MyUserInfo
          Public Overridable Property MyUserInfo() As MyUserInfo
              Get
                  Return m_MyUserInfo
              End Get
              Set(value As MyUserInfo)
                  m_MyUserInfo = Value
              End Set
          End Property
          Private m_MyUserInfo As MyUserInfo 
      End Class
  
      Public Class MyUserInfo
          Public Property Id() As Integer
              Get
                  Return m_Id
              End Get
              Set(value As Integer)
                  m_Id = Value
              End Set
          End Property
          Private m_Id As Integer
          Public Property FirstName() As String
              Get
                  Return m_FirstName
              End Get
              Set(value As String)
                  m_FirstName = Value
              End Set
          End Property
          Private m_FirstName As String
          Public Property LastName() As String
              Get
                  Return m_LastName
              End Get
              Set(value As String)
                  m_LastName = Value
              End Set
          End Property
          Private m_LastName As String
      End Class
  
      Public Class ToDo
          Public Property Id() As Integer
              Get
                  Return m_Id
              End Get
              Set(value As Integer)
                  m_Id = Value
              End Set
          End Property
          Private m_Id As Integer
          Public Property Description() As String
              Get
                  Return m_Description
              End Get
              Set(value As String)
                  m_Description = Value
              End Set
          End Property
          Private m_Description As String
          Public Property IsDone() As Boolean
              Get
                  Return m_IsDone
              End Get
              Set(value As Boolean)
                  m_IsDone = Value
              End Set
          End Property
          Private m_IsDone As Boolean
          Public Overridable Property User() As ApplicationUser
              Get
                  Return m_User
              End Get
              Set(value As ApplicationUser)
                  m_User = Value
              End Set
          End Property
          Private m_User As ApplicationUser 
      End Class
      Public Class MyDbContext
          Inherits IdentityDbContext(Of ApplicationUser)
          Public Sub New()
              MyBase.New("conn1") 'DefaultConnection
          End Sub
  
          Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
              MyBase.OnModelCreating(modelBuilder)
  
              ' Change the name of the table to be Users instead of AspNetUsers
              modelBuilder.Entity(Of IdentityUser)().ToTable("Users")
              modelBuilder.Entity(Of ApplicationUser)().ToTable("Users")
          End Sub
  
          Public Property ToDoes() As DbSet(Of ToDo)
              Get
                  Return m_ToDoes
              End Get
              Set(value As DbSet(Of ToDo))
                  m_ToDoes = Value
              End Set
          End Property
          Private m_ToDoes As DbSet(Of ToDo)
  
          Public Property MyUserInfo() As DbSet(Of MyUserInfo)
              Get
                  Return m_MyUserInfo
              End Get
              Set(value As DbSet(Of MyUserInfo))
                  m_MyUserInfo = Value
              End Set
          End Property
          Private m_MyUserInfo As DbSet(Of MyUserInfo)
      End Class
  
  
  End Namespace
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Based on a comment I also checked <a href="https://menononnet.wordpress.com/2011/03/07/create-database-permission-denied-in-database-master-microsoft-sql-server-error-262/" rel="nofollow noreferrer">here</a>.</p>
  
  <p>I don't really get why this is a role issue, since I'm reusing a connection string that is already working fine with updating other (non-identity related) tables. Also I don't get why the error refers to the <code>master</code> table as I'd expect that I'm not trying to connect to that in any way by the <code>manager.Find</code> method.</p>
  
  <p>Anyway, the user through which I'm currently testing is already assigned to the <code>sysadmin</code> role:</p>
  
  <p><a href="https://i.stack.imgur.com/oDshi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oDshi.png" alt="enter image description here"></a></p>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>Ok, thanks to Jeremy's comment below I'm a step closer...I needed to add user <code>IIS APPPOOL\.NET v4.5</code> to role <code>sysadmin</code>, because that was the user connecting as shown in SQL Server profiler (although I'm unsure about the security risks when adding this user to this role).
  Anyway, the Find method no longer throws an error and using SQL Server profiler I see the SQL statement is fired when I execute this code <code>Dim user As User = manager.FindByName(Trim(Username.Text))</code></p>
  
  <pre><code>exec sp_executesql N'SELECT TOP (1) 
  [Extent1].[Id] AS [Id], 
  [Extent1].[ApplicationId] AS [ApplicationId], 
  [Extent1].[MobileAlias] AS [MobileAlias], 
  [Extent1].[IsAnonymous] AS [IsAnonymous], 
  [Extent1].[LastActivityDate] AS [LastActivityDate], 
  [Extent1].[MobilePIN] AS [MobilePIN], 
  [Extent1].[LoweredEmail] AS [LoweredEmail], 
  [Extent1].[LoweredUserName] AS [LoweredUserName], 
  [Extent1].[PasswordQuestion] AS [PasswordQuestion], 
  [Extent1].[PasswordAnswer] AS [PasswordAnswer], 
  [Extent1].[IsApproved] AS [IsApproved], 
  [Extent1].[IsLockedOut] AS [IsLockedOut], 
  [Extent1].[CreateDate] AS [CreateDate], 
  [Extent1].[LastLoginDate] AS [LastLoginDate], 
  [Extent1].[LastPasswordChangedDate] AS [LastPasswordChangedDate], 
  [Extent1].[LastLockoutDate] AS [LastLockoutDate], 
  [Extent1].[FailedPasswordAttemptCount] AS [FailedPasswordAttemptCount], 
  [Extent1].[FailedPasswordAttemptWindowStart] AS [FailedPasswordAttemptWindowStart], 
  [Extent1].[FailedPasswordAnswerAttemptCount] AS [FailedPasswordAnswerAttemptCount], 
  [Extent1].[FailedPasswordAnswerAttemptWindowStart] AS [FailedPasswordAnswerAttemptWindowStart], 
  [Extent1].[Comment] AS [Comment], 
  [Extent1].[Email] AS [Email], 
  [Extent1].[EmailConfirmed] AS [EmailConfirmed], 
  [Extent1].[PasswordHash] AS [PasswordHash], 
  [Extent1].[SecurityStamp] AS [SecurityStamp], 
  [Extent1].[PhoneNumber] AS [PhoneNumber], 
  [Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed], 
  [Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled], 
  [Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc], 
  [Extent1].[LockoutEnabled] AS [LockoutEnabled], 
  [Extent1].[AccessFailedCount] AS [AccessFailedCount], 
  [Extent1].[UserName] AS [UserName]
  FROM [dbo].[AspNetUsers] AS [Extent1]
  WHERE ((UPPER([Extent1].[UserName])) = (UPPER(@p__linq__0))) OR ((UPPER([Extent1].[UserName]) IS NULL) AND (UPPER(@p__linq__0) IS NULL))',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'flo@outlook.com'
  </code></pre>
  
  <p>The strange thing is: when I execute it directly in SQL Server Management Studio I get a record returned, but in my code the variable <code>user</code> is <code>Nothing</code>....What can it be?</p>