解决DbContext对象创建问题

解决DbContext对象创建问题

方法一:

使用CallContext

public class BaseController : Controller
    {
        public MyContext db
        {
            get
            {
                var db = CallContext.GetData("DB") as MyContext;
                if (db == null)
                {
                    db = new MyContext();
                    CallContext.SetData("DB", db);
                }
                return db;
            }
        }
    }

 

方法二:

使用线程

 public class BaseController : Controller
    {
        public MyContext db
        {
            get
            {
                MyContext db = null;
                if (HttpContext.Items["DB"] == null)
                {
                    db = new MyContext();
                    HttpContext.Items["DB"] = db;
                }
                else
                {
                    db = HttpContext.Items["DB"] as MyContext;
                }
                return db;
            }
        }
    }

 

posted @ 2019-03-22 17:23  土豆哥  阅读(242)  评论(0编辑  收藏  举报