tags:

views:

38

answers:

1

Should the LINQ datacontext be stored in request.items for web apps?

+1  A: 

No, IMO. In particular, I'm quite a purest, so I don't think my UI should have anything to do with the data access. That is the job of a repository class. An a repository class should likewise have nothing to do with the http-request.

So by separation-of-concerns, the only logical answer here is "no".


Re being expensive (comments); it actually gains cost the longer you use it:

  • the object/identity tracker will slowly accumulate each unique record you fetch
  • the change tracker has more work to monitor
  • you get a lot more chance of stale (out-of-date) records (getting wrong data is a definite cost)

And by allowing it to live beyond the DAL, you also have to worry about threading (this is especially true for web-requests, where you can get all sorts of interesting combinations of requests for the same session).

LINQ-to-SQL doesn't offer much cache; it has limited support to short-circuit identity lookups to the identity manager (so if you ask for Single(x=>x.Id == 12345), and it has seen record 12345, it won't hit the database). However, most of the time it'll hit the database. And re the database, one of the bigger costs there is the cost of new connections; which is mitigated very effectively (for web apps) by the connection pooling on SqlConnection.

Marc Gravell
so then where would you store it? open/closing per call?
mrblah
I would, yes. If you have a few tightly-coupled operations at the data layer, then you might share it...
Marc Gravell
isn't it an expensive object like the session object in nhibernate?
mrblah
It *gains* expense as you use it; I'll update...
Marc Gravell