none
DataContext usage

    Question

  • I have a database with around 30 tables.
    I am planning on using Linq to SQL as my data layer.
    When i create a class to do all my CRUD tasks i will be creating a new dataContext in each method CRUD method.

    Should i create a new Datacontext for each method or is there better practice that i could follow?
    Friday, July 19, 2013 11:54 AM

Answers

  • I think you should create only one datacontext.

    Create a class that you pass on every form and which contains the datacontext.

    In this class, test to see if the datacontext has already been created, otherwise create it.

    Something like this :

         Private _dc As ApplicationDataContext
         Property DataContext() As ApplicationDataContext
            Get
                If Me._dc Is Nothing Then
                         Me._dc = New ApplicationDataContext
                End If
                Return Me._dc
            End Get
    
            Set(ByVal value As ApplicationDataContext)
                Me._dc = value
            End Set
        End Property
    

    • Marked as answer by Pure Deal Wednesday, July 24, 2013 9:01 AM
    Friday, July 19, 2013 2:11 PM

All replies

  • I think you should create only one datacontext.

    Create a class that you pass on every form and which contains the datacontext.

    In this class, test to see if the datacontext has already been created, otherwise create it.

    Something like this :

         Private _dc As ApplicationDataContext
         Property DataContext() As ApplicationDataContext
            Get
                If Me._dc Is Nothing Then
                         Me._dc = New ApplicationDataContext
                End If
                Return Me._dc
            End Get
    
            Set(ByVal value As ApplicationDataContext)
                Me._dc = value
            End Set
        End Property
    

    • Marked as answer by Pure Deal Wednesday, July 24, 2013 9:01 AM
    Friday, July 19, 2013 2:11 PM
  • Could i place the above code in a Must Inherit class and then use an Inherits statement in each class or does it have to be a property? Before you say "give it a try" i did and any inserts/selects didnt work :(
    Friday, July 19, 2013 3:04 PM
  • That's what I do. I have a "DataManager" class that all other classes Inherit.

    The "DataManager" class has a Property named "DataContext".

    What happens in your case ? Do you receive an error message ?

    Friday, July 19, 2013 3:44 PM