EF创建上下文对象HttpContext和CallContext

  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;
            }
        }
    }

posted @ 2019-03-22 21:56  执念、旧时光  阅读(562)  评论(0编辑  收藏  举报