dbcontext initialization
Private DemoContext db=new DemoContext ();
problem : When to release db object ?

use Using() 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 , hold EF Object into a thread , Create a new one Base controller , As other controller base class

Add namespace reference :
using System.Runtime.Remoting.Messaging;
Controller code :
public class BaseController : Controller { // Mode 1 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 2 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 new HttpContext example , Until the end of the request , The server will destroy this instance .