Opening a DbContext connection within an existing SqlConnection

﹥>﹥吖頭↗ 提交于 2019-12-01 21:23:40

问题


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?

For example:

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. Is the connection being reused in both cases, given that the connection string refers to the same SQL Server 2012 database in both cases?
  2. Is there any danger that such operation will require MSDTC?

回答1:


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.

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



来源:https://stackoverflow.com/questions/26274976/opening-a-dbcontext-connection-within-an-existing-sqlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!