What\'s the best practice in terms of setting up my DataContext for easy access in my extended LinqToSql classes?
For example, I have a \"User\" entity in my dbml a
As Rex M said, the datacontext is intended to be instantiated, used, and disposed for each logical transaction. Patterns like this are sometimes called a "unit of work".
The most common way (that I know of) to do this is to instantiate your datacontext in a using block. I haven't used VB in a while, but it should look something like this:
Using dc As New MyDataContext()
user = (From u in dc.Users Where u.ID = UserID).Single()
End Using
This not only reinforces the look of a transaction/unit of work (through the physical shape of the code), but it ensures calling Dispose() on your datacontext when the block ends.
See this MSDN page:
In general, a DataContext instance is designed to last for one "unit of work" however your application defines that term. A DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances at method scope or as a member of short-lived classes that represent a logical set of related database operations.