EF Code First - creating database - Login failed for user

匿名 (未验证) 提交于 2019-12-03 01:06:02

问题:

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:

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:

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

static MyDbContext()         {             Database.SetInitializer(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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!