"The noblest pleasure is the joy of understanding"   (Leonardo da Vinci)
Website banner

Static DataContext? No-no

It is necessary to reuse the DataContext object in an ASP.NET application, but the way to do it is a bit tricky. Especially if you have a multi-layered data model and you make several queries against the database.

The obvious - but wrong way - is to create a static instance of the DataContext somewhere in your business model. The reason this is wrong is that the static variable will remain there for successive calls to your web application. If something goes wrong in one request, for instance if an entity is updated but for some reason the SubmitChanges fails, then this failed object will still be in the DataContext when subsequent (or concurrent) requests to your site occur.

This blog has a nice approach to how the DataContext can be tied to the HttpContext.

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

In particular the comment by Richard Deeming using an extension method looks promising.

Leave a Reply

[[[ Copyright (C) Thor Asmund 1998-2008 ]]]