Using a DataContext static variable

前端 未结 2 745
隐瞒了意图╮
隐瞒了意图╮ 2021-01-06 07:26

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

相关标签:
2条回答
  • 2021-01-06 08:20

    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

    0 讨论(0)
  • 2021-01-06 08:21

    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.

    0 讨论(0)
提交回复
热议问题