I’m using the partial classes feature of Linq2SQL to add some helper methods to my objects.
The problem is that I need to perform some additional database queries in these helper methods, so I have to create a new DataContext every time.
I want to reuse a DataContext for all database operations within a single web service query.
If I keep the helper methods in a separate class, I simply initialize the context just once in the class constructor and reuse it for all methods.
With extended Linq2SQL classes I can’t figure out how to get a reference to the same DataContext that was used for retrieving the current object.
Indeed, you can’t really, as such. Not least, because LINQ-to-SQL can work with POCOs. You must handle your data-context manually, and keep hold of them if you want to use them at various points. One approach here could be to make the method available from the data-context rather than the leaf object – then you are forced to know the data-context.
In some cases, keeping a data-context available against a “request” or “context” object may be a good way to get around this, since that is usually trivially available.