Entity Framework Error – The server principle “user” is not able to access the database “master” under the current security context

I’m pretty new at Entity Framework and really haven’t even skimmed the surface of what it can do. But as a newbie, I encountered this error right from the start and my bet is other people have too. Let me first explain the setup of my environment.

I’ve created a code first entity framework application. I have created an Azure Server and database (doesn’t have to be Azure database), and created a SQL user so that they are db_owner on the database. On first running of my application I hit the following error: –

“The server principal “demouser” is not able to access the database “master” under the current security context.

Database ‘master’ on server ‘xxxxxxxx.westeurope1-a.worker.database.windows.net’ is not currently available. Please retry the connection later. If the problem persists, contact customer support, and provide them the session tracing ID of ‘6214BE0A-7962-4728-B0BE-B129401F98B0’.

Login failed for user ‘demouser’.”

So why does it need access to the master database?

It requires this to log into SQL server.  If the user database doesn’t exist and you want the code to create your database, you will also need to give your account dbo access to your master database, I don’t recommend doing this.

What is the solution?

Add the account to the master database so that it has public access. The SQL Script below is the full script I now use to create the account. The line highlighted is the line you need to run on against your master database to fix your error message.

use [master]
--Run within the master database.
-Create the Login account.
CREATE LOGIN demouser WITH password 'P@ssword123'
--This is the line you need
CREATE USER demouser FOR LOGIN demouser

--Run within your Database
use [demoDatabase]
CREATE USER demouser FOR LOGIN demouser
ALTER ROLE [db_owner] ADD MEMBER demouser