none
VS2008 Visual Basic: Constructor for global Linq datacontext RRS feed

  • Question

  • I have an application where several windows forms are performing CRUD functions on tables in a local SQLce database.  CRUD data operations in these forms are performed primarily by databound controls created automatically using the windows form designer, except for specialized data manipulation which utilizes Linq queries and code-behind logic.

    Since all of the form classes share the same database, dataset, and tables, I would like to try using a global datacontext which would be accessible from each of the windows forms.  My understanding of how to do this is to create public objects in a code module, but how do I do this when the database is not selected until run-time?  Currently, I am doing something like the following in each of the separate form classes:

        Private db As New DataContext(myConnectionString)
        Private rcTbl As Table(Of RentComp) = db.GetTable(Of RentComp)()
        Private scTbl As Table(Of SaleComp) = db.GetTable(Of SaleComp)()

    This approach implies the creation of separate and independent datacontexts in each form class, constructed from the state of the database when each form is loaded.  Although I have not seen any problems so far, I am nervous about the lack of synchronization among the different form classes, and the possibility that the duplicate datacontexts may not reflect some uncommited memory-resident change in the dataset somewhere.

    Would the use of a global datacontext be advisable in this situation, and how would I code it.  I have experimented with setting up a public datacontext in a code module, but I can't fully instantiate the dataset until the specific database connections string is known, and this cannot be determined until run-time (I have been successful in switching out run-time and design-time connection strings, but not with a global datacontext.  So far, I have created the following global variables is a code module, but I am fuzzy on how to instantiate the datacontext when the connection string is known:

        'setup global database objects
        Public dbRE As DataContext = Nothing
        Public tblRC As Table(Of RentComp) = Nothing
        Public tblSC As Table(Of SaleComp) = Nothing

    Does anyone have any ideas or suggestions for what the global datacontext constructor syntax would look like?

    Thanks, -BGood

    Thursday, June 25, 2009 7:56 PM