EntityConnection只能使用封闭的DbConnection构造

时间:2011-08-25 16:41:04

标签: .net entity-framework transactionscope sqlconnection objectcontext

“EntityConnection只能使用封闭的DbConnection构建” 这是我尝试构建提供开放连接的实体连接时遇到的问题。 有一个事务管理器打开,我不想打开一个新的连接,或者事务将被提升为dtc事务,因为我的理解是,如果我在多个entityConnections上使用单个SqlConnection,我不需要DTC。 / p>

所以,我的代码大致是这样的。

提前致谢...

    using (TransactionScope transactionScope = new TransactionScope())
{

    using (SqlConnection dwConn = GetDWConnection(user)) 
    {
        dwConn.Open();
        // I need to do some SQlConnection specific actions first

        //EntityConnection specific actions next
        Func1(dwConn);
        Func2(dwConn); //similar to Func1()
        Func3(dwConn); //Similar to Func1()

    }

}
    Func1(SqlConnection dwConn)
    {
        using (EntityConnection conn = GetSQLEntityConnection(sqlConnection))
        {
            ObjectContext objectContext = (ObjectContext)Activator.CreateInstance(objectContextType, new object[] { conn });
            //few actions
        }
    }
    private EntityConnection GetSQLEntityConnection(SqlConnection sqlConnection)
        {
        //few steps
            EntityConnection entityConnection = new EntityConnection(entityConnectionStringBuilder.ToString());

            EntityConnection sqlEntityConnection = new EntityConnection(entityConnection.GetMetadataWorkspace(),sqlConnection);
            return sqlEntityConnection;
        }

2 个答案:

答案 0 :(得分:2)

Jakub是完全正确的。您可以同时创建DbContextEntityConnection,并且已向其传递DbConnection

根据Diego B Vega’s post,在EF 6发布之前,此问题不会得到解决(here您可以投票支持)

解决方法是在涉及它的任何操作之前打开已初始化的EntityConnection

鉴于ObjectContext,您可以这样打开EntityConnection

((EntityConnection)objectContext.Connection).Open();

如果DbContext EntityConnection可从基础ObjectContext获得。代码可能是这样的:

class MyDbContext : DbContext
{
    public MyDbContext (DbConnection connection) 
                  : base (connection, contextOwnsConnection: true)
    {
        ((IObjectContextAdapter)this).ObjectContext.Connection.Open();
    }

    // …
}

class Program
{
    public static void Main()
    {
        var connection = new SqlConnection(CONNECTION_STRING);
        using (var database = new MyDbContext(connection))
        {
            Assert.IsTrue(connection.State == ConnectionState.Open);
        }
        Assert.IsTrue(connection.State == ConnectionState.Closed);
    }
}

答案 1 :(得分:0)

正如您已经发现的那样,您无法从已打开的连接中创建新的EntityConnection

不要反复传递SqlConnection并反复创建EntityConnection,而应重构代码并改为传递ObjectContextObjectContext是EF中的根对象,您应该优先于SqlConnection