Get DbContext entities and properties at runtime

The modelbuilder will first build all DbSets specified.
It will then build from any class objects that these DbSets refer to. This is more than you might think. Furthermore on some actions one of these other classes may have not been mapped correctly and cause the main program to crash, even if you were never interested in these classes.

To discover what classes and properties have been built at run-time use the following code:

    _
    Public Sub ProductsContextEntitiesBuiltList()
        Using context As New ProductsContext(ConnectionString.CurrentConnectionString)
            ContextEntitiesBuiltList(context)
        End Using
    End Sub

    Private Sub ContextEntitiesBuiltList(context As Entity.DbContext)
        Dim objContext = CType(context, IObjectContextAdapter).ObjectContext
        Dim workspace As MetadataWorkspace = objContext.MetadataWorkspace
        Dim tables As IEnumerable(Of EntityType) = workspace.GetItems(Of EntityType)(DataSpace.CSpace)
        For Each table In tables
            Debug.WriteLine(table.FullName)

            For Each p In table.Properties
                Debug.WriteLine("   " + p.Name)
            Next
        Next

        Debug.WriteLine("")

        'Or
        'For Each myEntity In objContext.MetadataWorkspace.GetItems(Of EntityType)(DataSpace.CSpace).ToList
        '    Debug.WriteLine(myEntity.FullName)
        'Next
    End Sub

Use modelBuilder.Ignore(Of <entity) 'to stop building those not required.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: