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

时间:2011-07-19 18:52:08

标签: c# entity-framework entity-framework-4.1 dbcontext

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

实体框架(使用4.1版本中的新DbContext API)似乎不希望保持明确打开的连接打开。旧ObjectContext API会保持连接按预期打开并documented

由于DbContext API只使用了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();
        }
    }
}

1 个答案:

答案 0 :(得分:14)

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

using (var connection = ...)
{
    using (var context = new TestDataContext(connection, false))
    {
        ...
    }
}