【发布时间】:2011-07-19 18:52:07
【问题描述】:
我正在尝试重用现有的数据库连接,以便可以使用 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();
}
}
}
【问题讨论】:
-
如果在 Open() 之后但在第一个查询之前放置一个 Assert,那么结果是什么?我想知道这里的问题是否实际上只是它返回了错误的值,而不是实际关闭并重新打开连接。
-
@Tridus,您建议的 Assert 以
Open的预期结果通过。 -
我意识到这是一篇旧文章,但我只是在阅读 Julia Lerman 的书,她使用的语法是 context.Connection.Open() (即上下文和连接之间没有数据库)。只是一个想法。
标签: c# entity-framework entity-framework-4.1 dbcontext