在现有的SqlConnection中打开DbContext连接 [英] Opening a DbContext connection within an existing SqlConnection

查看:219
本文介绍了在现有的SqlConnection中打开DbContext连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否应该阻止在现有ADO.NET SqlConnection 中打开实体框架的 DbContext 连接,前提是它们都使用相同的连接字符串,即在完全相同的数据库上运行?

I'm interested if opening an Entity Framework's DbContext connection within an existing ADO.NET SqlConnection should be discouraged, provided that they both use the same connection string, i.e. operate on the exactly same database?

例如:

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new System.TimeSpan(0, 30, 0)))
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        DoStuffWithEF(connectionString);
        ...
    }
}

void DoStuffWithEF(string connectionString)
{
    using (var context = new MyCodeFirstDbContext(connectionString))
    {
        // basic LINQ queries ...
    }
}





  1. 连接字符串在两种
    情况下都引用同一SQL Server 2012数据库的情况下,在两种情况下都可以重用连接吗?

  2. 这种操作是否需要MSDTC?


推荐答案

连接字符串不是连接。您永远不会将实际的连接传递到上下文,因此必须创建一个新的连接。结果,该事务将升级为分布式事务,以覆盖两个连接。

The connection string is not the connection. You never pass the actual connection to the context, so it has to create a new one. As a consequence, the transaction will escalate to a distributed transaction in order to cover both connections.

您需要使用适当的构造函数。在这种情况下,将只有一个本地事务,而无需将其升级为分布式事务。

You need to pass the actual connection object to the context, using the appropriate constructor. In this case there will be only a single local transaction and no need to escalate it to a distributed transaction.

在EF6 +中,您可以简单地传递连接对象。将您的方法更改为:

In EF6+ you can simply pass the connection object. Change your method to this:

void DoStuffWithEF(SqlConnection connection)
{
    using(var context=new MyCodeFirstDbContext(connection,false)
    {
    // ...
    }
}

在以前的版本中,您无法传递需要一些不愉快体操的开放式连接,如此处

In previous versions you couldn't pass an open connection which required some unpleasant gymnastics, as described here

这篇关于在现有的SqlConnection中打开DbContext连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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