Search code examples
asp.netasp.net-mvcrazorwebmatrix

How to get column names WebMatrix.Data


Trying to figure out how to get the column names from the SQL statement. Saw something online that says this works, but surely it doesn't:

 var rows=db.Query("select * from users");

 <ul>
     @foreach(var col in rows)
     {
         <li>@col.name</li>
     }
 </ul>

This displays the value only if there is a column with the name name, but I'd like the actual column name if possible.

Anyone know how to get all the column names using WebMatrix.Data ?

EDIT:

Looks like the DynamicRecord Class exposes the column names, just wondering how it applies. http://msdn.microsoft.com/en-us/library/webmatrix.data.dynamicrecord(v=vs.111).aspx


Solution

  • Ok let me explain this for you.

    I have created a new project and tested it in the Visual Studio and it works. You need to udnerstand the basics about the DynamicRecord and the property of the Columns.

    Here is the code that I have used,

    @{ 
        var db = Database.Open("StarterSite");
        var selectQuery = "SELECT * FROM UserProfile";
        var result = db.Query(selectQuery);
    }
    

    In the HTML I did this,

    <div>
        @foreach (var row in result)
        {
            <p>@row.Columns[0]</p>
        }
    </div>
    

    When it executed, since the DynamicRecord.Columns property is an IList<string> generic type, so you should understand that you can read their properties through a simple indexation. Like the one I have done, it will read the first column from the List of the strings that was sent down to the user.

    Now when it executed, since the very first column was Email, it gave me the following output on screen.

    enter image description here

    You can get others from the list too. Just update the index number. :-)

    http://msdn.microsoft.com/en-us/library/webmatrix.data.dynamicrecord.columns(v=vs.111).aspx