views:

214

answers:

2

With linq, do you create a single dbContext per request like nHibernate requires (for performance reasons, creating sessions in nhibernate from what I understand are an expensive call).

i.e. in my asp.net-mvc application, I may for a given action, hit the database 5-10 times on seperate calls. Do I need to create a context and re-use it for the entire request?

A: 

When I did a small app using LinqToSql, I found the app was very sluggish when i did a create-use-dispose of a DatabaseContext object each time I had to hit the database. When I moved to sharing the DBContext across multiple requests... the app suddenly came back to life w.r.t. responsiveness.

Here's a question that I posted which is relevant

Gishu
+5  A: 

DataContexts are intended to be used for a single set of actions interacting with your database. I know, that's vague. Their usage is situational. If you are doing related, or specifically sequential activities, then one DataContext is probably good for you. If you are doing unrelated or parallel activities, consider using a DataContext for each activity.

Consider a few guidelines:

  • Entities retrieved by one DataContext can only be used (read: updated, deleted, etc.) by that same DataContext. If you need to match up objects across separate DataContexts, you'll have to do something such as running a LINQ query to select objects with the same primary key.
  • LINQ to SQL uses optimistic concurrency.
  • Dispose of the DataContext when you are done with it (letting it go out of scope and be garbage collected is fine)
  • Do not use a static or shared DataContext.
JoshJordan
This is the right answer. DataContexts are pretty lightweight objects and should be kept around for fairly atomic operations. After which get rid of them. Using statements for the win.
Simucal