CREATE DATABASE permission denied in database 'master'. Cannot attach the file 'C:\co\App_Data\xxx.mdf' as database 'xxx'

4

I have a problem with attaching the database with information about users. I'm trying to move the asp.net mvc4 project to the IIS. MS SQL Server 2008 Express.

<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-comvc4-20130423110032;Integrated Security=true;AttachDBFilename=|DataDirectory|\aspnet-comvc4-20130423110032.mdf;" providerName="System.Data.SqlClient" />

Error: 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.

Exception Details: System.Data.SqlClient.SqlException: CREATE DATABASE permission denied in database 'master'. Cannot attach the file 'C:\co\App_Data\aspnet-comvc4-20130423110032.mdf' as database 'aspnet-comvc4-20130423110032'.

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): CREATE DATABASE permission denied in database 'master'.
Cannot attach the file 'C:\co\App_Data\aspnet-comvc4-20130423110032.mdf' as database 'aspnet-comvc4-20130423110032'.]
   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.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +69
   System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +30
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +317
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +889
   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) +225
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +37
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +558
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +67
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1052
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +167
   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
   WebMatrix.Data.Database.EnsureConnectionOpen() +46
   WebMatrix.Data.<QueryInternal>d__0.MoveNext() +67
   System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +164
   WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +98
   WebMatrix.WebData.DatabaseWrapper.QuerySingle(String commandText, Object[] parameters) +14
   WebMatrix.WebData.SimpleMembershipProvider.CheckTableExists(IDatabase db, String tableName) +54
   WebMatrix.WebData.SimpleMembershipProvider.CreateTablesIfNeeded() +50
   WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +70
   WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
   WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +52
   comvc4.Filters.SimpleMembershipInitializer..ctor() +197

[InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588]
   comvc4.Filters.SimpleMembershipInitializer..ctor() +254

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +6
   System.Threading.LazyHelpers`1.ActivatorFactorySelector() +68
   System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
   System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +106
   comvc4.Filters.InitializeSimpleMembershipAttribute.OnActionExecuting(ActionExecutingContext filterContext) +24
   System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +69
   System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +22
   System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +492
   System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +22
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +190
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +182
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +445
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +287
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +338
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +282
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +129
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +236
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

I already have one successful connection to another database in the same project:

<add name="codatabaseEntities" connectionString="metadata=res://*/Models.coModel.csdl|res://*/Models.coModel.ssdl|res://*/Models.coModel.msl; provider=System.Data.SqlClient; provider connection string=&quot;Data Source=x.x.x.x,xxxx; Network Library=DBMSSOCN; Integrated Security=false;Initial Catalog=codatabase; User Id=sa2; Password=123456;&quot;" providerName="System.Data.EntityClient"/>

But I need both. The first is the default database in asp.net project. The second is mine. I've tried so many ways, nothing helps. Could anyone help me, please.

asp.net
sql
connection-string
asked on Stack Overflow Jun 10, 2013 by mistique • edited Jun 11, 2013 by mistique

3 Answers

2

I've tried harder. This one worked for me:

<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-comvc4-20130423110032.mdf;Integrated Security=false;AttachDBFilename=|DataDirectory|\aspnet-comvc4-20130423110032.mdf;User Id=sa2; Password=123456;" providerName="System.Data.SqlClient"/>

And I triple checked access permissions.

Thanks, everyone!

answered on Stack Overflow Jun 11, 2013 by mistique
2

I notice that with my connection string there is this User Instance=True so you could try adding that to the connection string if you were looking to continue to use integrated security.

would look something like

<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-comvc4-20130423110032.mdf;Integrated Security=false;AttachDBFilename=|DataDirectory|\aspnet-comvc4-20130423110032.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

I realize this is an old question but may still be helpful to someone

answered on Stack Overflow Jul 7, 2015 by workabyte
0

I had the same issue with my app using ASP.NET Core 2.1.

i.e. SqlException: CREATE DATABASE permission denied in database 'master'. Cannot attach the file as database...

I solved the problem not with my connection string but with permissions in the database. My connection string now looks like this in appsettings.json after following a solution from another post to get my SQL Express file closely located where I wanted it with my code. See How to set the right AttachDbFilename relative path in ASP.NET Core?

"ConnectionStrings": {
       "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DB_xxxxx_itemsubdb;User Id=DB_xxxx_itemsubdb_user;Password=xxxxxxx;Integrated Security=false;MultipleActiveResultSets=true;AttachDbFileName=%CONTENTROOTPATH%\\Data\\xxxxxxxDB.mdf;"
  },

So, for the fix, In Microsoft SQL Server Management Studio, I ended up adding the following permission to my user after login in as sa.

Security > Logins > Select your user and right click > Properties > Click Server Roles > Select the checkbox for dbcreator.

Good luck.

answered on Stack Overflow Mar 15, 2019 by levteck

User contributions licensed under CC BY-SA 3.0