The Syrian
The Syrian

Reputation: 203

Retrieving Database Schema Linq to SQL VB.Net

I want to retrieve each column name and data type then check if the columns is foreign key then query they key table of that relation !!! could be done ?? I googled for 3 days I know that I have to use Mappping model OR Reflection or both ,,,, but i cant do it .

I will simplify what i need assuming : TABLE1 hase foreign key( COL3) refer to the primary key (COL1) in TABLE0 :

  1. iterate TABLE1 Columns check EACH columns if it is a foreign key ( also get its data type)

  2. Get the relation to determine the associated table(TABLE0)

  3. retrieve the primary key tables (TABLE0)

Upvotes: 2

Views: 516

Answers (1)

The Syrian
The Syrian

Reputation: 203

I got it I make a function that return the type of each foreign key and the related table class type

Private Function GetForeignKeyTables(ByVal myTableType As Type) As List(Of myForeignKeys)

    Dim myDx = New Tester.DataClasses1DataContext
    Dim mymodel As New AttributeMappingSource

    Dim myAsociations = mymodel.GetModel(GetType(DataClasses1DataContext)).GetTable(myTableType).RowType.Associations

    Dim asc = From m In myAsociations Where m.IsForeignKey
               Select New myForeignKeys With {.KeyDataType = m.ThisKey.First.DbType, .RelatedTableType = m.OtherType}

    Return asc.ToList

End Function

Private Class myForeignKeys
    Property KeyDataType As String
    Property RelatedTableType As MetaType

End Class 

But I still need to retrieve the data from those related table .

I mean how to create an instance of the class from its MetaType variable?

Upvotes: 1

Related Questions