声明静态、非静态、私有或公共数据库上下文有何含义?
将数据库上下文 ex: mydbEntities 声明为以下内容(在每种情况下)有什么含义:
public static mydbEntities db = new mydbEntities ();
public mydbEntities db = new mydbEntities();
私有静态 mydbEntities db = new mydbEntities();
私有 mydbEntities db = new mydbEntities();
我正在使用 ASP.NET MVC 2。 谢谢你!
What are the implications (in each case) of declaring a database context ex: mydbEntities as either:
public static mydbEntities db = new mydbEntities ();
public mydbEntities db = new mydbEntities ();
private static mydbEntities db = new mydbEntities ();
private mydbEntities db = new mydbEntities ();
I'm using ASP.NET MVC 2.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
static
在这里会非常糟糕。数据上下文不能很好地与线程配合使用,因此您希望每次都将其丢弃以避免过度使用。您可以使用与当前http上下文相关的静态属性。 这可能有道理。那么它只是一个公共静态属性。然而,许多人更喜欢 IOC 和基于实例的上下文之类的东西;或位于存储接口后面的上下文。选择权在你。
注意:另一个选项是线程静态的,但不应该假设您的所有请求都由同一线程提供服务。所以也不要这样做。
static
would be very very bad here. Data-context does not play nicely with threading, plis you want to throw it away each time to avoid overuse. You could use a static property that relates to the current http context. That might make sense. Then it is just a public static property.Many people prefer things like IOC and instance-based contexts, however; or contexts that sit behind the storage interface. The choice is yours.
Note: another option is thread-static, but it should not be assumed that all of your request is serviced by the same thread. So don't do that either.
这实际上是一个 Ling 2 SQL 问题,而不是一个 ASP.NET MVC 问题(我假设这就是您正在使用的问题,或者可能是实体框架)。
在 Web 应用程序中使用 L2SQL 时,一些人提倡使用 DataContext 每个 Web 请求模式。也就是说,您创建一个 DataContext 并在整个当前执行的 Web 请求期间保留它。为此,您需要将其存储在 HttpContext.Items 集合中,如下所示
HttpContext.Current.Items.Add("myKey", new MyDataContext());
...并像这样检索它
MyDataContext context = HttpContext.Current.Items["myKey"] as MyDataContext;
您可能应该创建一些帮助程序类,以便更轻松地访问 DataContext 并隐藏此代码。
This is really a Ling 2 SQL question rather than an ASP.NET MVC question (I assume that's what you're using, or maybe it's Entity Framework).
A few people advocate the DataContext per web request pattern when using L2SQL in a web application. That is you create a single DataContext and keep it for the duration of the entire currently executing Web request. To do this you need to store it in the HttpContext.Items collection like so
HttpContext.Current.Items.Add("myKey", new MyDataContext());
...and retrieve it like so
MyDataContext context = HttpContext.Current.Items["myKey"] as MyDataContext;
You probably ought to create some helper class for easier access to your DataContext and hide this code away.