Are Multiple DataContext classes ever appropriate? Are Multiple DataContext classes ever appropriate? asp.net asp.net

Are Multiple DataContext classes ever appropriate?


I disagree with John's answer. The DataContext (or Linq to Entities ObjectContext) is more of a "unit of work" than a connection. It manages change tracking, etc. See this blog post for a description:

Lifetime of a LINQ to SQL DataContext

The four main points of this blog post are that DataContext:

  1. Is ideally suitedfor a "unit of work" approach
  2. Is also designed for"stateless" server operation
  3. Is not designed for Long-lived usage
  4. Should be used very carefully afterany SumbitChanges() operation.

Considering that, I don't think using more than one DataContext would do any harm- in fact, creating different DataContexts for different types of work would help make your LinqToSql impelmentation more usuable and organized. The only downside is you wouldn't be able to use sqlmetal to auto-generate your dmbl.


I'd been wrangling over the same question whilst retro fitting LINQ to SQL over a legacy DB. Our database is a bit of a whopper (150 tables) and after some thought and experimentation I elected to use multiple DataContexts. Whether this is considered an anti-pattern remains to be seen, but for now it makes life manageable.


I think John is correct.

"My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources"

How do you support that statement? What is your experiment that shows that a large DataContext is a performance bottleneck? Having multiple datacontexts is a lot like having multiple databases and makes sense in similar scenarios, that is, hardly ever. If you are working with multiple datacontexts you need to keep track of which objects belong to which datacontext and you can't relate objects that are not in the same data context. That is a costly design smell for no real benefit.

@Evan "The DataContext (or Linq to Entities ObjectContext) is more of a "unit of work" than a connection"That is precisely why you should not have more than one datacontext. Why would you want more that one "unit of work" at a time?