EF Code First - creating database - Login failed f

2020-02-12 06:18发布

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?

1条回答
手持菜刀,她持情操
2楼-- · 2020-02-12 06:44

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.

查看更多
登录 后发表回答