Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First - creating database - Login failed for user

I originally had a EF code first set up that was connecting to an existing database. This was working fine.

I then made a couple changes to a POCO and decided to have code first generate the new database for me.

Getting error: Cannot open database \"MyDatabase\" requested by the login. The login failed.\r\nLogin failed for user 'DOMAIN\username'.

I deleted the old database, but I did not change the connection string:

<add name="MyDatabaseContext" connectionString="Data Source=localhost;Initial Catalog=MyDatabase;Integrated Security=True;" providerName="System.Data.SqlClient" />

I have a sql server 2008 instance on my local machine and my domain username is in "sysadmin" role.

I tried various Database initializers and I get the same error for all. It is failing on the first query call, but code first does not create the database. I can point the connection string to a copy of the old database (before changes) and it will run fine, except that it is my old schema even though I specified the DropCreateDatabaseAlways initializer. This is not making sense, and not following what I experienced on my home machine working with code first.

Using Visual studio 2012 and EF5.

I need to be able to have code first generate a new database. What is going on?

like image 404
Adam Avatar asked Feb 20 '13 17:02

Adam


1 Answers

Found out I had a static constructor in my DbContext class, which was overriding the database initializer.

static MyDbContext()
        {
            Database.SetInitializer<MyDbContext>(null);
        }

Code first reverse engineer will put this in so you don't overwrite your existing database. When I switched I wasn't thinking about it.

Hope this will help someone else out.

like image 199
Adam Avatar answered Sep 28 '22 06:09

Adam