998*_*823 2 c# asp.net ef-code-first dbcontext
我在这里找到stackoverflow上的帖子之后设置了我的DbContext模型.
这是目前的设置......
public static class DbContext
{
public static MyDbContext Db
{
get
{
if (!HttpContext.Current.Items.Contains("_db"))
{
HttpContext.Current.Items.Add("_db", new MyDbContext());
}
return HttpContext.Current.Items["_db"] as MyDbContext;
}
}
}
Run Code Online (Sandbox Code Playgroud)
上下文在end_request上的global.asax中处理,如下所示:
void Application_EndRequest(object sender, EventArgs e)
{
var db = (MyDbContext)HttpContext.Current.Items["_db"];
if (db != null)
db.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
这样,在我的系统中,我可以访问Db DbContext.Db.xxxx
到目前为止,一切都在本地运行,但是,我还没有在生产环境中测试过多个用户.
我的顾虑...
我在stackoverflow上阅读了这篇文章,现在让我担心多个用户访问静态上下文可能存在数据问题.这应该关注我还是我的安装方式好吗?
设置好吗......
我的解决方案不使用静态DbContext.DbContext(或任何需要的东西)存储在HttpContext.Current.Items集合中(即当前特定于HTTP请求的),该属性等效于一个方法调用,它将从此集合中检索上下文并在需要时对其进行实例化.选择此集合是为了它的安全性,并且很容易从任何地方(即从Application_EndRequest事件)引用它,因此我们可以在完成后处理它.
你链接的帖子有很大的不同,因为它描述了你使用的帖子static field.该字段显然将在所有用户之间共享,这将是一个大问题.
| 归档时间: |
|
| 查看次数: |
1396 次 |
| 最近记录: |