实体框架数据库连接是不可预测的 [英] Entity framework database connection is unpredictable

查看:88
本文介绍了实体框架数据库连接是不可预测的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个班级中使用了几个上下文。我没有使用任何全球背景。我需要每个上下文保持打开状态,因为我在执行多个查询并在处理上下文之前在同一方法中保存多次。最初我声明如下



context = new Entities();



多个查询..



保存..



查询...



context.Dispose();



问题是,实体框架在save()命令后关闭连接。然后我决定做以下事情:



context = New Entities(); context.Database.Connection.Open()



多个查询..



save ..



查询...



context.Database.Connection.Close()context.Dispose();



这在我的开发机器上工作正常。一旦我在不同的机器上尝试相同的程序,它就会表现得非常奇怪。有时打开需要5-6分钟,有时需要20-25分钟。但是一旦它启动,其他一切工作正常。



因为它在我的开发机器上工作正常然后我遗漏了一些东西。我最近几天一直试着没有运气。



我们非常感谢任何帮助。



谢谢。

I have used several context within one class. I have not used any global context. I need each of my context to stay open as I am doing multiple queries and saving more than once in the same method before disposing the context. Initially I declared as below

context = new Entities();

multiple queries..

save..

query...

context.Dispose();

The problem with this is, entity framework closes the connection after save() command. Then I decided to do following:

context = New Entities(); context.Database.Connection.Open()

multiple queries..

save..

query...

context.Database.Connection.Close() context.Dispose();

This works fine in my development machine. As soon as I try the same program in a different machine, it behaves very strange. Sometimes it takes 5-6 minutes to open and in sometimes 20-25 minutes. But once it starts everything else works fine.

As it is working fine in my development machine then I am missing something. I have been trying for last few days without any luck.

Any help will be much appreciated.

Thanks.

推荐答案

而不是像你这样使用上下文



context = new Entities();

多个查询..

保存..

查询...

context.Dispose();





这样使用



使用(var context = new Entites( ))

{//从这里开始连接打开

多个查询..

保存..

查询。 ..

} //在此括号之前连接已关闭



因此您应该可以进行任何查询更新或其他任何内容当你进入上面的区块时。



也没有你不需要手动处理现在为你处理的上下文
instead of using you context like this

context = new Entities();
multiple queries..
save..
query...
context.Dispose();


use like this

using ( var context = new Entites())
{ //starting here connection opens
multiple queries..
save..
query...
} // before this bracket the connection is closed

so you should be able to do any queries updates or whatever as long as you inside the above block.

also no you have no need to manually dispose of context thats now handled for you


这篇关于实体框架数据库连接是不可预测的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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