DbContext 的自定义连接打开/关闭

Ari*_*iac 7 c# database-connection entity-framework-core ef-core-3.1

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)

Jin*_*kur 8

这是执行事务的标准方式。\n您可以组合多个查询。

\n\n
using (var context = new SchoolContext())\n{\n    var std = new Student()\n    {\n        FirstName = "Bill",\n        LastName = "Gates"\n    };\n    context.Students.Add(std);\n\n    // or\n    // context.Add<Student>(std);\n\n    context.SaveChanges();\n\n   std = context.Students.First<Student>(); \n    std.FirstName = "Steve";\n    context.SaveChanges();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

ef core 可以使用相同的连接或不同的连接或基于连接池。\nef core 具有连接和断开连接的事务模式。我认为这适合您。\在断开连接的情况下数据与在连接的情况下有点不同。在断开连接的场景中,DbContext 不知道断开连接的实体,因为添加或修改的实体超出了当前 DbContext 实例的范围。因此,您需要将断开连接的实体附加到具有适当 EntityState 的上下文,以便对数据库执行 CUD(创建、更新、删除)操作。

\n\n

下图说明了断网场景下的CUD操作:

\n\n

根据上图,断开连接的实体(DbContext 未跟踪的实体)需要使用适当的 EntityState 连接到 DbContext。例如,新实体的已添加状态、已编辑实体的已修改状态和已删除实体的已删除状态,这将在调用 SaveChanges() 方法时在数据库中产生 INSERT、UPDATE 或 DELETE 命令。

\n\n

为了在断开连接的情况下使用 Entity Framework Core 将记录插入、更新或删除到数据库表中,必须执行以下步骤:

\n\n

使用适当的 EntityState(例如已添加、已修改或已删除)将实体附加到 DbContext\n调用 SaveChanges() 方法\n以下示例演示使用上述步骤将新记录插入数据库:

\n\n
//Disconnected entity\nvar std = new Student(){ Name = "Bill" };\n\nusing (var context = new SchoolContext())\n{\n    //1. Attach an entity to context with Added EntityState\n    context.Add<Student>(std);\n\n    //or the followings are also valid\n    // context.Students.Add(std);\n    // context.Entry<Student>(std).State = EntityState.Added;\n    // context.Attach<Student>(std);\n\n    //2. Calling SaveChanges to insert a new record into Students table\n    context.SaveChanges();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

在上面的示例中,std 是 Student 实体的断开连接实例。context.Add() 方法将 Student 实体附加到具有已添加状态的上下文。SaveChanges() 方法构建并执行以下 INSERT 语句:

\n\n

exec sp_executesql N\'SET NOCOUNT ON;\n https://www.entityframeworktutorial.net/efcore/ saving-data-in-disconnected-scenario-in-ef-core.aspx saving-data-in-disconnected-scenario-in-ef-core.aspx \n 这些是重要的方法。

\n\n
public DbContext(DbConnection existingConnection, bool contextOwnsConnection)\npublic DbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection)\n
Run Code Online (Sandbox Code Playgroud)\n\n

EF6 及未来版本中的行为\n对于 EF6 及未来版本,我们采取的方法是,如果调用代码选择通过调用 context.Database.Connection.Open() 来打开连接,那么它有充分的理由这样做,并且框架将假设它想要控制连接的打开和关闭,并且将不再自动关闭连接。

\n\n

笔记

\n\n

这可能会导致连接长时间打开,因此请小心使用。

\n\n

我们还更新了代码,以便 ObjectContext.Connection.State 现在可以正确跟踪底层连接的状态。

\n\n
  using System;\nusing System.Data;\nusing System.Data.Entity;\nusing System.Data.Entity.Core.EntityClient;\nusing System.Data.Entity.Infrastructure;\n\nnamespace ConnectionManagementExamples\n{\n    internal class DatabaseOpenConnectionBehaviorEF6\n    {\n        public static void DatabaseOpenConnectionBehavior()\n        {\n            using (var context = new BloggingContext())\n            {\n                // At this point the underlying store connection is closed\n\n                context.Database.Connection.Open();\n\n                // Now the underlying store connection is open and the\n                // ObjectContext.Connection.State correctly reports open too\n\n                var blog = new Blog { /* Blog\xe2\x80\x99s properties */ };\n                context.Blogs.Add(blog);\n                context.SaveChanges();\n\n                // The underlying store connection remains open for the next operation  \n\n                blog = new Blog { /* Blog\xe2\x80\x99s properties */ };\n                context.Blogs.Add(blog);\n                context.SaveChanges();\n\n                // The underlying store connection is still open\n\n           } // The context is disposed \xe2\x80\x93 so now the underlying store connection is closed\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

https://learn.microsoft.com/en-us/ef/ef6/fundamentals/connection-management?redirectedfrom=MSDN

\n

  • 我相信 OP 是在寻找“EF Core”解决方案? (2认同)