我正在尝试重用现有的数据库连接,以便我可以使用TransactionScope不调用MSDTC 来执行多个数据库操作.
实体框架(使用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(); …Run Code Online (Sandbox Code Playgroud) EF Core 打开和关闭DbConnection为每个查询打开和关闭 a,除非您传入已打开的连接。
我有很多小疑问,因此我不想每次都打开和关闭连接,而是希望每次保持连接打开五秒钟,同时为每个查询/命令重用该连接。(上面链接的问题的解决方案使连接在 DBContext 的整个生命周期内保持开放状态。)
抛开锁定/并发问题,我可以在哪里注入自定义连接解析/打开逻辑DbContext?就像是
before executing query:
if connection is not open
open
set timer to fire close request in five seconds
take lock on connection (to prevent closing)
execute query
release lock
Run Code Online (Sandbox Code Playgroud)