I have a project with a number of different classes querying and modifying data in a common set of tables. I've set up a .dbml file which provides us with a DataContext class. My question is whether a single instance of the DataContext should be used by all objects, or whether multiple instances are safe to use. I'm also wondering about thread safety in the case of a single DataContext, and whether access to it's methods should be synchronized.
Rick Strahl has a nice article about your options: http://www.west-wind.com/weblog/posts/246222.aspx.
See also: LINQ to SQL - where does your DataContext live?.
You may want a slightly different strategy for each type of deployment - web, desktop, windows service...
Summarized, your options are:
I opted for a DataContext per data object. It may not be the fanciest solution but it works in all deployment environments.
I use an new instance of DataContext for every transaction.
Reusing old instances can be troublesome, and will bloat the content of the DataContext, since any item that has been loaded at some time, will have to be tracked - your app will get slower and slower, bloating up memory.
If you need an item longer than for a transaction, you can detach it from the DataContext by cloning the item, and can reattach it later to a new and fresh DataContext using Attach().
I even can clone an item, send it over the network with WCF, get it back in some later call, attach it to a new DataContext and save the changes (of course I need a timestamp column for this).
The DataContext class is lightweight enough that you can instantiate it over and over. This makes thing simpler when accessing entity objects within a single method. If you need to access the same LINQ objects from different classes and methods while keeping them attached to the DataContext for tracking purposes, it's also okay to keep a single instance.
The problem with using a single data-context object is that you can get in trouble if you've added some changes to it's queue, and want to do a roll-back on just some of those queued changes.
That's why I use a data-context object for each of my classes--my User
class has it's own data-context, my Application
class has it's own, and so forth.
This pattern eliminates most troubles of doing roll-backs in my projects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With