EF代码首先创建数据库 - 用户登录失败 [英] EF Code First - creating database - Login failed for user

查看:95
本文介绍了EF代码首先创建数据库 - 用户登录失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最初设置了一个EF代码,它连接到一个现有的数据库。



然后,我对POCO进行了一些更改,并决定让代码首先为我生成新的数据库。



获取错误:无法打开登录请求的数据库\MyDatabase\。登录失败。\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

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

我的本​​地机器上有一个sql server 2008实例,我的域用户名是sysadmin角色



我尝试过各种不同的数据库初始化程序,所有这些都是同样的错误。它在第一个查询调用失败,但代码首先不创建数据库。我可以将连接字符串指向旧数据库的副本(更改前),它将运行正常,但它是我的旧模式,即使我指定了DropCreateDatabaseAlways初始化程序。这是没有意义的,而不是跟随我在家用机器上使用代码的经历。



使用Visual studio 2012和EF5。



我需要能够让代码首先生成一个新的数据库。发生了什么?

解决方案

发现我在DbContext类中有一个静态构造函数,它覆盖了数据库初始化程序。 / p>

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

代码第一个逆向工程师将把它放在这里,所以你不要覆盖你现有的数据库。当我切换我没有想到它。



希望这将帮助别人出去。


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?

解决方案

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.

这篇关于EF代码首先创建数据库 - 用户登录失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆