views:

144

answers:

3

If I'm extending OnCreated for a LINQ to SQL table object, is it possible to get a reference to the data context to which the table belongs? For example, if I add a property to the data context:

Partial Class MyDataContext

    Private _myValue As String
    Public ReadOnly Property MyValue As String
       Get
           Return _myValue
       End Get
       Set(ByVal value As String)
           _myValue = value
       End Set
    End Property

End Class

is there any way to access that value in the create event of the table, i.e.:

Partial Class MyTable

    Private Sub OnCreated()
        Dim contextValue = [data_context_reference_here].MyValue
    End Sub

End Class

I don't want the property on the data context to be Shared, because it could be different per instance. I've been pouring over the designer code to figure out where the reference might be, but no luck yet. Any ideas?

A: 

A simple google search (linq event data context) would have led you to where this question was already asked and answered:

http://stackoverflow.com/questions/317114/determine-the-source-datacontext-for-a-linq-to-sql-query

Dave
+1  A: 

There are no generated table objects in LINQ to SQL--only row objects, of which the DataContext owns one Table(Of TRowType) per. So the partial OnCreated method you implement is in a row class, and will be called whenever a row is created.

Generated row objects implement INotifyPropertyChanged and INotifyPropertyChanging, but are not derived from any base class. Since OnCreated takes no parameters, there is no way for the row to determine (via that method) which Table it belongs to, much less which DataContext it was created for.

You'll have to find some other way to do what you want.

Ben M
+1  A: 

I will say it is an incorrect pattern for Linq 2 SQL

In Linq2sql, it is supposed that any row object like your MyTable can be created without context. Later you can attach it to a table (with a specified context)

For example

Dim myTable as new MyTable()
dataContext.GetTable(Of MyTable).Attach(myTable)

So in reality, you should not create any logic inside MyTable classes that will depend on datacontext that was used to create this object, because some of them can be created without dataContexts, some can be attached and detached...

Bogdan_Ch