我正在尝试重用现有的数据库连接,以便我可以在TransactionScope
不调用 MSDTC 的情况下使用 a 执行多个数据库操作。
实体框架(使用DbContext
4.1 版本中的新 API)似乎不想保持显式打开的连接打开。旧ObjectContext
API 保持连接按预期打开并记录在案。
由于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();
}
}
}