dbcontext Initialization
Private DemoContext db=new DemoContext ();
problem: When to releasedb object?

UseUsing() Method, Each call will cause frequent connections to close the database

You might think that the object is globally unique using singleton mode, If multiple users operate the same database, So it must be globally unique within the thread

Solve:MVC in, holdEF Object into a thread, Build a new one.Base Controller, As other controller base class

Add namespace reference:
using System.Runtime.Remoting.Messaging;
Controller code:
public class BaseController : Controller { // One way public DBContext db { get { //
Get from current thread DBContext object DBContext db = CallContext.GetData("DB") as DBContext; if
(db ==null) { db = new DBContext(); // Put in data slot, Make the thread unique CallContext.SetData("DB",
db); }return db; } } // Mode two public DBContext DB2 { get { DBContext db = null; if
(HttpContext.Items["db1"] == null) { db = new DBContext(); HttpContext.Items["
db1"] = db; } else { db = HttpContext.Items["db1"] as DBContext; } return db; }
} }
CallContext: Is a specialized collection object similar to the thread local store of a method call, And provide a unique data slot for each logical execution thread. Data slots are not shared between call contexts on other logical threads

HttpContext: Requests from different users, The server will create a newHttpContext Example, Until the end of the request, The server will destroy this instance.