none
Is there a way to obtain the # of columns in table using LINQ?

    Question

  • I would like to be able to know at runtime how many columns are in a given Table.

    I would then use this value to say know how many data fields I would have to inspect/print out.

    This is for a VB.NET Application.

    Thanks.

    Friday, May 09, 2014 3:53 PM

Answers

  • Here is some code that will get you on the right track.  For this to work though you have to do a dummy query.  Otherwise you would have to query the system tables (which you may or may not have Sql Server permission to do.

            Dim dc As New DataClasses1DataContext
    
            Dim query = (From rs In dc.RSongInfos Select rs.Album, rs.Artist Take 1)
    
            Dim rec = query.FirstOrDefault
            Dim qt As Type = rec.GetType()
    
            Dim props = qt.GetProperties()
    
            '  here the count of props is the number of columns
            Dim numcols = props.Count
    

    The second method uses a class defined for a Linq table object.

            Dim otherMethod = GetType(RSongInfo)
            Dim otherprops = otherMethod.GetProperties()
    


    Lloyd Sheen

    • Marked as answer by Fan Farron Friday, May 09, 2014 10:41 PM
    Friday, May 09, 2014 10:31 PM

All replies

  • Here is some code that will get you on the right track.  For this to work though you have to do a dummy query.  Otherwise you would have to query the system tables (which you may or may not have Sql Server permission to do.

            Dim dc As New DataClasses1DataContext
    
            Dim query = (From rs In dc.RSongInfos Select rs.Album, rs.Artist Take 1)
    
            Dim rec = query.FirstOrDefault
            Dim qt As Type = rec.GetType()
    
            Dim props = qt.GetProperties()
    
            '  here the count of props is the number of columns
            Dim numcols = props.Count
    

    The second method uses a class defined for a Linq table object.

            Dim otherMethod = GetType(RSongInfo)
            Dim otherprops = otherMethod.GetProperties()
    


    Lloyd Sheen

    • Marked as answer by Fan Farron Friday, May 09, 2014 10:41 PM
    Friday, May 09, 2014 10:31 PM
  • The 2nd method will do just fine.  Thank you so much.
    Friday, May 09, 2014 10:42 PM