简体   繁体   中英

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

You can use the GetDynamicMemberNames method to obtain the "columns" (which have been converted to dynamic properties)

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

 <ul>
     @foreach(var item in rows.First().GetDynamicMemberNames())
     {
         <li>row[item]</li>
     }
 </ul>

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.

在此输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM