views:

592

answers:

2

I have recently inheited a ASP.Net app using Linq2SQL. Currently It has its DataContext objects declared as static in every page, and i create them the first time i find they are null (singleton, sort of).

I need comments if this is good or bad. In situations when I only need to read from the DB and in situations where i need to write as well.

How about having just one DataContext instance for the entire application?

+2  A: 

I use to have one DataContext per request, but it depends on the scenarios you're facing. I think the point with L2S was to use it with the unit of work pattern, where you have a context per ... well unit of work. But it doesn't work well in larger applications as it's pretty hard to reattach entities to a new context later.

Rick Strahl has a real good introduction to the topic here:

http://www.west-wind.com/weblog/posts/246222.aspx

One thing I can say I have had problems with in the past, is to have one context to both read and write scenarios. The change tracking done in the datacontext is quite an overhead when you are just reading, which is what most webapps tends to do most of the time. You can make the datacontext readonly and it will speed up things quite a bit - but then you'll need another context for writing.

asgerhallas
+1  A: 

One DataContext per application would perform badly, I'm afraid. The DataContext isn't thread safe, for starters, so even using one as a static member of a page is a bad idea. As asgerhallas mentioned it is ideal to use the context for a unit of work - typically a single request. Anything else and you'll start to find all of your data is in memory and you won't be seeing updates without an explicit refresh. Here are a couple posts that talk to those two subjects: Identity Maps and Units of Work

OdeToCode