Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a DataContext static variable

I have recently inherited an 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?

like image 839
Midhat Avatar asked Dec 31 '22 01:12

Midhat


1 Answers

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

like image 136
OdeToCode Avatar answered Jan 08 '23 15:01

OdeToCode