13

TransactionScopeMSDTC を呼び出さずに を使用して複数のデータベース操作を実行できるように、既存のデータベース接続を再利用しようとしています。

Entity Framework ( 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();
        }
    }
}
4

1 に答える 1

14

接続を制御したい場合は、コンテキストの前に作成してコンテキストに渡す必要があります。そうしないと、接続は制御できません。次のようなものを試してください:

using (var connection = ...)
{
    using (var context = new TestDataContext(connection, false))
    {
        ...
    }
}
于 2011-07-19T19:21:38.663 に答える