EF建立上下文物件HttpContext和CallContext

Claire_ljy發表於2020-04-04

  public class BaseController : Controller
    {
        /// <summary>
        /// 方法1
        /// </summary>
        public TestModelContext db
        {
            get {
                TestModelContext db = CallContext.GetData("DB") as TestModelContext;
                if (db == null)
                {
                    db = new TestModelContext();
                    CallContext.SetData("DB", db);

                }
                return db;

            }
        }
        /// <summary>
        /// 方法2
        /// </summary>
        public TestModelContext DB2
        {
            get {
                TestModelContext db = null;
                if (HttpContext.Items["db1"] == null)
                {
                    db = new TestModelContext();
                    HttpContext.Items["db1"] = db;
                }
                else {
                    db = HttpContext.Items["db1"] as TestModelContext;
                }
                return db;
            }
        }
    }

轉載於:https://www.cnblogs.com/yuesebote/p/10581267.html

相關文章