我正在尝试重用现有的数据库连接,以便我可以使用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(); } } }
解决方法
如果要控制连接,则必须在上下文之前创建它,并将其传递给上下文,否则连接不受您的控制.尝试像:
using (var connection = ...) { using (var context = new TestDataContext(connection,false)) { ... } }