DbContext不会保持连接打开以便重复使用

GWB*_*GWB 13 c# entity-framework entity-framework-4.1 dbcontext

我正在尝试重用现有的数据库连接,以便我可以使用TransactionScope不调用MSDTC 来执行多个数据库操作.

实体框架(使用DbContext4.1版本中的新API)似乎不希望保持明确打开的连接打开.旧的ObjectContextAPI保持连接按预期打开并记录.

由于DbContextAPI只是ObjectContext在引擎盖下使用,我预计会有同样的行为.有谁知道这个改变是有意还是已知问题?我无法在任何地方找到它.

public void ConnectionRemainsOpen()
{
    using (var context = new TestDataContext())
    {
        try
        {
            Assert.AreEqual(ConnectionState.Closed, context.Database.Connection.State);

            context.Database.Connection.Open();

            var firstRecord = context.Table3.FirstOrDefault();

            // this Assert fails as State == ConnectionState.Closed
            Assert.AreEqual(ConnectionState.Open, context.Database.Connection.State);

            var newRecord = new Table3
            {
                Name = "test",
                CreatedTime = DateTime.UtcNow,
                ModifiedTime = DateTime.UtcNow
            };

            context.Table3.Add(newRecord);

            context.SaveChanges();

            // this Assert would also fail
            Assert.AreEqual(ConnectionState.Open, context.Database.Connection.State);
        }
        finally
        {
            if (context.Database.Connection.State == ConnectionState.Open)
                context.Database.Connection.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Lad*_*nka 14

如果要控制连接,则必须在上下文之前创建连接并将其传递给上下文,否则连接不在您的控制之下.尝试类似的东西:

using (var connection = ...)
{
    using (var context = new TestDataContext(connection, false))
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)