简体   繁体   中英

Using VS2012 Database Projects: Cannot open database “my_database” requested by the login

I'm trying to get a VS2012 Database Project up and running for an existing product. I schema compared my database to populate my new database project and everything looked good. It appears to deploy fine with Visual Studio, no errors, but when I try to run my app against the freshly deployed database I get the following error:

Cannot open database "my_database" requested by the login. The login failed.

I've looked into this extensively and found some bizzare behavior I don't understand. If I execute the following sql after deploying my database, everything starts working:

DROP SCHEMA [my_app_user] 
GO
DROP USER [my_app_user] 
GO
CREATE SCHEMA [my_app_user]
GO
CREATE USER [my_app_user] FOR LOGIN [my_app_user] WITH DEFAULT_SCHEMA=[my_app_user]
GO
ALTER ROLE [my_app_role] ADD MEMBER [my_app_user];
GO

The odd thing is, this code is in my database project too, exactly as shown sans the drop statements. It creates all these things when I deploy but it does not work. Another odd behavior is when I open the login for the user in Sql Server Management Studio 2012 and look at the User Mapping for the login, it's not mapped. I can check the box for my database and it all looks good, but when I click ok and go back into that same window, it's not checked again. Running the above script makes the User Mapping window look good.

UPDATE: I moved the create statements for login/schema/user and the alter statement for role into the post deploy scripted used by the database project and now it's publishes to the database just fine. The Database Projects, however, seem to want to put these statements in with the rest of the schema, as opposed to post deploy, so I'd still like to know what, if anything, I can do to resolve this weirdness..

What is going on here and what can I do to fix this? Thanks for any help!!

You need to associated the user to the role in your post deployment scripts:

http://msdn.microsoft.com/en-us/library/aa833199(v=vs.100).aspx

This sounds like a permissions issue. Does the security context that the database is deployed with have the permissions to run this sql statement?

DROP SCHEMA [my_app_user] 
GO
DROP USER [my_app_user] 
GO
CREATE SCHEMA [my_app_user]
GO
CREATE USER [my_app_user] FOR LOGIN [my_app_user] WITH DEFAULT_SCHEMA=[my_app_user]
GO
ALTER ROLE [my_app_role] ADD MEMBER [my_app_user];
GO

Take a peek in the SQL Server logs for the point in time when the database is being deployed, and also look in the application log on the box that does the deployment to see if there is a more detailed error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM