在用于连接实体的使用块中
如何在调用其他方法时重用连接?
所以我有:
using (SampleEntities entities = new SampleEntities()) {
entities.Connection.Open();
SomeMethod();
...
}
void SomeMethod() {
using (SampleEntities entities = new SampleEntities())
{
// I want to be able to use the existing connection before the method call, any ideas?
}
}
答案 0 :(得分:3)
为什么没有
void SomeMethod(SampleEnities context)
并传递给它;让第一个“使用”理清处理。
善,
丹
答案 1 :(得分:2)
您可以使用以下文档创建ConnectionScope
和DataContextScope
:http://msdn.microsoft.com/en-us/magazine/cc300805.aspx
这意味着你可以这样做:
using (var connection = container.Resolve<IDbConnection>())
using (var context = container.Resolve<IMyDataContext>())
{
context.Connection = connection;
// Do some stuff...
context.SubmitChanges();
}
这就是我所做的,它有效对待!这意味着context.SubmitChanges()
仅在堆栈顶部调用。因此,允许您调用使用连接/上下文的方法,而不必担心将它们作为参数传递。
答案 2 :(得分:0)
如果您使用相同的连接字符串,则会为您处理连接池。
即使您使用的是dispose,它也不会关闭连接。它将它返回池以供下次使用。
对于事务范围,您希望使用相同的连接,因此在处置该连接之前,您必须在事务中执行所有操作。
这样:
using(...){
call methods execute transaction...
You can pass the connection into other methods here for use,
just make sure it doesn't get disposed in that method.
commit..
}//connection is disposed.
答案 3 :(得分:0)
void SomeMethod(SampleEntities entities){
var do_dispose = false;
try{
if(entities == null) { entities = new SampleEntities();
entities.Connection.Open();
do_dispose = true; }
// do with entity object...
}
finally{
if(do_dispose && entities != null){
entities.Dispose();
}
}
}
用法:
using(SampleEntities entities = new SampleEntities()){
entites.Connection.Open();
SomeMethod(entities);
...
}
答案 4 :(得分:0)
DbContext
构造函数的重载允许确定是否应当在处理上下文时处置现有连接。您需要将DbConnection
传递给上下文并要求它保持连接存活:
using(SqlConnection con = new SqlConnection(conStr))
{
using(var context1 = new SampleEntities(existingConnection:con, contextOwnsConnection:false)
{
}
using(var context2 = new SampleEntities(existingConnection:con, contextOwnsConnection:false)
{
}
}
更改上下文以将参数传递给基数:
class SampleEntities : DbContext
{
public SampleEntities(DbConnection existingConnection, bool contextOwnsConnection) :
base(existingConnection, contextOwnsConnection) )
{
}
}