Entity Framework 4.3.1 无法创建(/打开)数据库 [线程异常?]

Entity Framework 4.3.1 failing to create (/open) a database [Threading Anomaly?](Entity Framework 4.3.1 无法创建(/打开)数据库 [线程异常?])
本文介绍了Entity Framework 4.3.1 无法创建(/打开)数据库 [线程异常?]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不久前我在一个 MVC 3 项目中使用过 EF 4.1(Code First),效果很好.

I've used EF 4.1 (Code First) in an MVC 3 project a while back, and it was good.

今天我尝试在一个 WinForms 项目中使用 EF 4.3.1(Code First)并遇到了一些真正的巫术:(我从事的原始项目是 WinForms,但同样的事情适用于附加控制台应用程序代码.)

Today I tried using EF 4.3.1 (Code First) in a WinForms project and encountered some real voodoo: (The original project I was working on was WinForms, however the same thing is true for the attached Console Application code.)

当尝试将一个简单的类输入数据库时​​,我得到以下异常:无法打开登录请求的数据库测试".登录失败.用户[ComputerName][Administrator]"登录失败.

When trying to enter a simple class into the database, I get the following exception: Cannot open database "Test" requested by the login. The login failed. Login failed for user '[ComputerName][Administrator]'.

我已尝试检查 SQL Server (2008 R2) 配置,但我的用户确实拥有服务器上的所有权限.

I've tried checking the SQL Server (2008 R2) configurations but my user does have all the permissions on the server.

注意:当我第一次运行应用程序时,数据库确实存在.

NOTE: The Database does not exist when I first run the application.

即使下面的示例代码也不起作用:

Even the following sample code does not work :

class Program
{
    public static void Main()
    {
        var person = new Person { Name = "Nathan" };
        using (var db = new MyContext())
        { //#1
            db.Persons.Add(person);
            db.SaveChanges();
        }
        Console.Write("Person saved !");
        Console.ReadLine();
    }
}

public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public MyContext()
        : base("Data Source=localhost;Database=Test;Integrated Security=True;")
    { }
}

我尝试重新安装 EF 4.3.1 - 无济于事.重新启动 SQL-Server 也没有效果.

I've tried re-installing EF 4.3.1 - to no avail. Restarting the SQL-Server also had no effect.

注意:我注意到周围有很多类似的问题,但没有一个与我的相同并且已回答 - 我希望我会幸运在这里:)

NOTE: I've noticed quite a lot of similar questions around, but none are both the same as mine and answered - here's me hoping I'll get lucky here :)

澄清一下:被拒绝访问的用户是机器的所有者(本地管理员).

To clarify: The user being denied access is the Owner (local administrator) of the machine.

我一直在进行一些实验,发现一些很奇怪的东西:

I've been running a few experiments and I've found something quite strange:

如果我在标记为#1"的行暂停程序并通过 Watch 窗口检查 db.Database.Exists() 的值,它会告诉我:函数评估需要所有线程运行" 使用那个小wavey 按钮,我可以单击它使其运行所有线程.

If I pause the program at the line marked "#1" and check the value of db.Database.Exists() via the Watch window, It tells me: "The function evaluation requires all threads to run" with that little wavey button I can click to make it run all threads.

如果我点击该按钮,函数的计算结果为 False.

If I click on that button the function evaluates to False.

现在我可以做 2 件事情了:

Now I can do 2 things:

  1. 继续执行:在这种情况下,我得到了完全相同的异常.
  2. 从 Watch 窗口执行 db.Database.Create():在这种情况下,程序成功运行到最后,我看到了在我的 SQL 管理中创建的数据库、表和行工作室.
  1. Continue execution: In this case I get the exact same exception.
  2. Execute db.Database.Create() from the Watch window: In this case the program runs successfully to the end and I see the Database, Table and Row created in my SQL Management Studio.

似乎是一个简单的解决方案,对吧?错了!

Seems like a simple solution, right? Wrong!

我尝试通过调用 db.Database.CreateIfNotExists(); 来为数据访问添加前缀,但随后我在该行得到了完全相同的异常.

I've tried prefixing the data access with a call to db.Database.CreateIfNotExists(); but then I get the exact same exception on that line.

db.Database.Initialize(true); 也没有效果...

注意:如果通过上述方法创建数据库,我可以从那时起正确使用它,所以这至少是半个安慰:P 当然,问题是什么当我添加 DropCreateIfModelChangesDropCreateAlways 初始化程序时发生(因为我正在积极开发模型).

NOTE: If by using the above method I create the database, I can use it properly from that point onwards, so that's at least half a consolation :P The problem is, of course, what happens when I add a DropCreateIfModelChanges or DropCreateAlways Initalizer (since I'm in the middle of active development of the model).

谢谢.

[我怀疑这更像是实体框架问题而不是 SQL Server.]

[I'm suspecting it's more of a Entity Framework problem than SQL Server.]

推荐答案

如果你碰巧打开了抛出异常时中断"选项(Debug->Excptions),调试时会看到这个异常.EF 正在尝试连接到数据库,但由于数据库尚不存在而失败,因此引发了异常.由于打开了上述选项,您会看到异常.此异常实际上被实体框架捕获,然后 EF 将连接到主数据库以创建它在第一步中尝试连接的数据库.创建数据库后,它将再次使用原始连接字符串与数据库通信.因此,您可以按 F5 继续调试,因为该异常是将被处理的第一次机会异常,或者禁用关闭抛出异常时中断",这将导致仅针对未处理的异常而不是所有异常中断被抛出.

You can see this exception when debugging if you happen to have "break when exception is thrown" option (Debug->Excptions) turned on. EF is trying to connect to the database but it fails since database does not exist yet so an exception is thrown. You see the exception due to the option above turned on. This exception is actually caught by the Entity Framework and EF will then connect to master database to create the database it was trying to connect in the first step. Once the database is created it will again use the original connection string to talk to the database. So, you can either press F5 to continue debugging since the exception is a first chance exception that will be handled or disable turn off "breaking when exception is thrown" which will result in breaking only for exceptions that are not handled rather than all exception that are thrown.

这篇关于Entity Framework 4.3.1 无法创建(/打开)数据库 [线程异常?]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)