views:

62

answers:

2

Hello,

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!

+2  A: 

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.

Marc Gravell
Ok. I think i understand. So static is bad because of the "thread"ing issue. I'm asking in the context of an asp.net-mvc application. Let me be more specific... I usually create a "private oddeedbEntities db = new oddeedbEntities();" in the controller class and use it in actions of that controller. Is this ok? What are the implications of having it public?
basilmir
@basilmir - public fields should *generally* be avoided anyway - perfer properties when possible (which is almost always). But as long as it isn't static it isn't going to matter *hugely* either way. The nice thing of a property is that you can, for example, do lazy initialization, so you only get a data-context when (or: if) you actually need one - i.e. when the `get` finds the field is null.
Marc Gravell
A: 

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.

Sunday Ironfoot
I'm asking in the context of an asp.net-mvc application. Let me be more specific... I usually create a "private oddeedbEntities db = new oddeedbEntities();" in the controller context and use it in actions of that controller. Is this ok? What are the implications of having it public?
basilmir
basilmir: Can you confirm whether or not you're using Linq 2 SQL?
Sunday Ironfoot
I'm not using Linq 2 SQL. I am using ADO.net Entity Framework.
basilmir