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

 

转载于:https://www.cnblogs.com/zlp520/p/10579603.html

你可能感兴趣的:(解决DbContext对象创建问题)