What are the implications of declaring a static, non-static, private or public database context?

What are the implications of declaring a static, non-static, private or public database context?

What are the implications (in each case) of declaring a database context ex: mydbEntities as either:

  1. public static mydbEntities db = new mydbEntities ();

  2. public mydbEntities db = new mydbEntities ();

  3. private static mydbEntities db = new mydbEntities ();

  4. private mydbEntities db = new mydbEntities ();

I'm using ASP.NET MVC 2. Thank you!

How to Inject HTML on ASP.NET MVC master page


Adding a custom httpmodule to route to MVC or custom handler selectively
static would be very very bad here. Multiple websites, Single sign-on designData-context does not play nicely with threading, plis you want to throw it away each time to avoid overuse. How to check the Condition hereYou could use a static property this relates to the current http context. Routing based on requested datatype in ASP.NET MVCThat might make sense. jquery selection problemThen it is just a public static property.. ASP.net MVC - Stop page rendering until JQuery finished Many people prefer things like IOC and instance-based contexts, however; or contexts this sit behind the storage interface. Tricking ASP.NET into Thinking Request is Ajax Request for jQuery File UploadThe choice is yours.. Note: ananother option is thread-static, although it should not be assumed this all of your request is serviced by the same thread. So don't did this either..


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 did 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 any helper class for easier access to your DataContext and hide this code away..

85 out of 100 based on 40 user ratings 195 reviews