3

I have a function, and inside that I am creating a DataContext() everytime the function is called. What is the cost of creating a new DataContext(). Can I create a static DataContext() and use it everywhere. Because The DataContext has a full recording of all the changes when SubmitChanges() fails, is there a way I can remove those specific changes from the DataContext when SubmitChanges() fails. My Question is which is better Creating static Datacontext() or Creating whenever its needed?

sri
  • 1,005
  • 1
  • 12
  • 26

1 Answers1

6

This topic has been discussed quite a bit and you should read this article about DataContext lifetime management. The short answer is that DataContext is meant to be used for a unit of work, typically a single request. DataContext objects are cheap to construct and there is no database overhead to creating one.

The main reason to avoid a shared instance of DataContext is because of thread safety and change tracking. Each modification you make to a repository object is captured and translated into update/insert/delete operations when you call SubmitChanges(). This feature breaks down when using a single DataContext object.

BC.
  • 24,298
  • 12
  • 47
  • 62
  • @BC: So if there are no update/insert/delete operations, i.e. if my application is Query Only, can I use the `static readonly DataContext()` – sri Jul 06 '11 at 06:40
  • It's safe to say yes. Keep in mind that you can optimize different contexts for different purposes. For example, the `AssociateWith` load options. Sometimes, it can be helpful to specify multiple data contexts to support different load options. Also, if you aren't doing any Update/Insert/Delete ops you can turn off object tracking to boost performance. I think it's `ObjectTrackingEnabled = false;` http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.associatewith.aspx – BC. Aug 23 '11 at 17:50