Sql-server – The server principal “” is not able to access the database “” under the current security context

Securitysql-server-2008

When I try to install a new database, I'm getting this error from SQL Server 2008.

The server principal "<mydbuser>" is not able to access the database "<mydatabase>" under the current security context.

I looked it up and it says it has something to do with orphaned users when doing a restore. This connection has nothing to do with a restore, it's a brand new database, user and connection, so why am I getting this problem?

Also the process I'm using to create the database and user/login, is the same for all of my databases, so why does this occur sometimes?

Any ideas?

Thanks.

EDIT: per request here's some code that fails, but understand that this works with every other application I've built. Also this is built into an ASP.NET MVC application.

System.Web.Management.SqlServices.Install(
    config.Database.DataSource.Trim(), 
    config.Database.UserName, 
    config.Database.Password, 
    config.Database.InitialCatalog, 
    System.Web.Management.SqlFeatures.All);


if (!Roles.RoleExists(role.Name))
    Roles.CreateRole(role.Name);  <-- this fails

Oh, another thing that doesn't make sense is that the database in the error message is not the database I'm trying to install to. It is one of the databases in this SQL Server instance (along with a bunch of others) but it's completely different. I can't figure out where it's getting this.

Example: the database I'm trying to install to is 'Rapper' and the database shown in the error message is 'GPS'. Why?

Best Answer

I can't create any comment yet. I don't have the required reputation. So I will post an answer!!!

You can view orphanage users in a database using:

exec sp_change_users_login 'report'

And it also might be because the default database of you login try:

exec sp_helplogins 'Login1'

You can change the default db with:

ALTER LOGIN Login1 WITH DEFAULT_DATABASE=test1